2017-04-18 68 views
0

我有一個唯一元素uniqueID的數組,它與ContentBlock數組中的對象的「ID」屬性匹配。到目前爲止,我的代碼遍歷uniqueID和contentBlock數組,並查找uniqueID中的元素值是否等於contentBlock中的ID值。通過對象循環以打印特定屬性?

如果uniqueID等於ID值,但我不確定如何在下面的forEach循環中打印這些多個屬性,我想現在返回對象的屬性標題,年齡和狀態(NOT ID)在這方面指導我?

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

我建議您使用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);

+0

有沒有寫這個使用_.filter從underscore.js的另一種方式?我是新來誘惑JS,所以我不知道如何。 – Tyler

+0

@Tyler Underscore過濾器的工作原理非常相似,但有什麼意義。繼續使用純js。 –