我有一系列独特元素,uniqueID,与" ID"匹配。对象的属性是contentBlock数组。到目前为止,我的代码遍历uniqueID和contentBlock数组,并查找uniqueID中的元素值何时等于contentBlock中的ID值。
如果uniqueID等于ID值,我想现在返回对象的属性标题,年龄和状态(NOT ID),但不确定如何在我的forEach循环中打印这些多个属性,有人可以指导我这个?
var uniqueID = ["a", "c"];
var contentBlock = [
{
title: "John",
age: 24,
state: "NY",
ID: "a"
},
{
title: "Jane",
age: 27,
state: "CA",
ID: "b"
},
{
title: "Joe",
age: 32,
state: "NY",
ID: "c"
},
{
title: "Carl",
age: 43,
state: "MI",
ID: "d"
}
]
uniqueID.forEach(function (item) {
contentBlock.forEach(function(tile) {
if (item === tile.ID) {
//return these properties of each object identified as unique
console.log(tile.title);
console.log(tile.age)
console.log(tile.state)
}
})
})
答案 0 :(得分:0)
我建议你改用Array#filter
。
var contentBlock = [{title:"John",age:24,state:"NY",ID:"a"},{title:"Jane",age:27,state:"CA",ID:"b"},{title:"Joe",age:32,state:"NY",ID:"c"},{title:"Carl",age:43,state:"MI",ID:"d"}], uniqueID = ["a", "c"],
hash = contentBlock.filter(v => uniqueID.indexOf(v.ID) > -1),
res = hash.map(v => Object.assign({}, {title: v.title, age: v.age, state: v.state}));
console.log(res);