[英]Compare array of objects by property with key of another object
I want to compare the data.examples array object name.value property value with wcObject.notCoveredList key, If the key matches I want to push all matched values of wcObject to an array inorder to display in UI. 我想将data.examples数组对象name.value属性值与wcObject.notCoveredList键进行比较,如果键匹配,我想将wcObject的所有匹配值推入数组以便在UI中显示。 If the key doesn't match, I want the name.desc property value of data.examples array object to be pushed by removing the not covered text at the end.
如果键不匹配,我希望通过删除末尾未覆盖的文本来推送data.examples数组对象的name.desc属性值。
data = {
examples : [
{
name: {
value:"someOne",
desc: "some random word not covered"
},
type: {
value:"General",
desc:"General"
}
}, {
name: {
value:"secondOne",
desc: "second on in the queue not covered"
},
type: {
value:"General",
desc:"General"
}
}, {
name: {
value:"thirdOne",
desc: "third one from the last not covered"
},
type: {
value:"General",
desc:"General"
}
}
]
}
wcObject = {
notCoveredList : [
{ someOne: "anyone can start " },
{ secondOne: "second One cannot start" },
{ thirdOne: "third One can be allowed" }
]
}
So, this code: 因此,此代码:
wcObject.notCoveredList
, and make them keys on a single object (with an undefined value), so that we can look up those keys with a single hasOwnProperty() call instead of iterating over an array when we need to filter. wcObject.notCoveredList
所有键,并使其成为单个对象(具有未定义值)的键,以便我们可以通过单个hasOwnProperty()调用来查找这些键,而无需在需要时遍历数组过滤。 data.examples
array to either its own name.desc
property or [stripped of ' not covered'] name.value
property. data.examples
数组的每个成员映射到其自己的name.desc
属性或[stripped name.value
cover'] name.value
属性。 . 。
wcNotCoveredKeys = wcObject.notCoveredList.reduce((memo, item) => {
// value is empty for all, we only care about keys.
memo[Object.keys(item)[0]] = undefined;
return memo;
}, {})
// having built up our lookup table of those not covered, we continue:
forUI = data.examples.map(example => {
if (wcNotCoveredKeys.hasOwnProperty(example.name.value)) {
return example.name.value;
}
else {
notCoveredString = example.name.desc;
cutOutIndex = notCoveredString.indexOf(' not covered');
return notCoveredString.slice(0, cutOutIndex)
}
});
(updated to integrate string slicing) (已更新以集成字符串切片)
Just to be clear: if you removed the second item from wcObject.notCoveredList, then the output you'd get in forUI (given the example data structures/values you provided) would be 只是要清楚一点:如果您从wcObject.notCoveredList中删除了第二项,那么您将在forUI中获得的输出(鉴于您提供的示例数据结构/值)
["someOne", "second on in the queue", "thirdOne"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.