我有一个字典对象,其填充如下:
const myDictionaryElement = this.myDictionary["abc"];
这里,myDictionaryElement
具有以下值:
ACheckStatus: "PASS"
QVVStatus: "READY"
VVQStatus: "READY"
QTTStatus: "READY"
QBCTTStatus: "READY"
CStatus: "FAIL"
我想创建一个对象,这样所有的key-value
对,其密钥在中间具有匹配的VV
,都应该存储在对象valuesVV
中,如下所示:
const valuesVV = { QVVStatus: "READY" };
类似地,密钥中间有匹配TT
的所有key-value
对都应存储在对象valuesTT
中,如下所示:
const valuesTT = { QTTStatus: "READY", QBCTTStatus: "READY" } ;
对于密钥中间没有匹配VV
和TT
的所有key-value
对,应按如下方式存储在对象valuesOther
中:
const valuesOther = { ACheckStatus: "PASS", VVQStatus: "READY", CStatus: "FAIL" } ;
为了实现about输出,我使用hasOwnProperty
作为字典,但它不工作
const valuesVV = myDictionaryElement.hasOwnProperty('*VV*'); // It is returning boolean false. The desired output is { QVVStatus: "READY" }
您可以通过创建一个函数来概括它,该函数接受dict和匹配数组,如下所示:
const dict = {
ACheckStatus: "PASS",
QVVStatus: "READY",
VVQStatus: "READY",
QTTStatus: "READY",
QBCTTStatus: "READY",
CStatus: "FAIL"
};
const matching = ['VV', 'TT', 'SS'];
function matchInput(input, matches) {
// will have matched object in the index of the match and those without a match
// at the end
const res = [];
Object.keys(input).forEach(key => {
// flag if the key wasn't matched to add it to no matches object
let matched = false;
matches.forEach((match, i) => {
if (key.indexOf(match) > 0) {
matched = true;
if (!res[i]) res[i] = {};
res[i][key] = input[key];
}
});
if (!matched) {
if (!res[matches.length]) res[matches.length] = {};
res[matches.length][key] = input[key];
}
});
return res;
}
这个想法是检查每个键,并将其插入正确的桶(对象(
您应该过滤对象键并只选择您需要的键,然后使用reduce创建一个新对象:
const vvItems = Object.keys(dictElement)
.filter(key => key.indexOf('VV')>= 1)
.reduce((o, key) => { o[key] = dictElement[key]; return o; }, {})