我有一个这样的数组:
data = [
{id:343, article:'yes', image:'ok'},
{id:35, article:'ko', image:'twe'},
{id:212, article:'ere', image:'efe'},
{id:90, article:'fefe', image:'fe'}
]
我试图遍历数组对象,然后获取id等于某个数字的id
,article
和image
数据。因此,例如,我想在id等于id
时抓取article
,image
和90
。
我能够辨别该数组以及该id是否存在:
data.forEach(function(key,value){
if (key['id'] === 343) {
//how to grab rest of this object?
}
})
但是从那里我不知道如何获取其余的对象数据。
我将如何处理?任何帮助将不胜感激。
答案 0 :(得分:1)
value
从object
获取key
data = [
{id:343, article:'yes', image:'ok'},
{id:35, article:'ko', image:'twe'},
{id:212, article:'ere', image:'efe'},
{id:90, article:'fefe', image:'fe'}
]
var result={}
data.forEach(function(item){
if (item['id'] === 343) {
result=item;
}
});
console.log(result.id,result.article,result.image);
data = [
{id:343, article:'yes', image:'ok'},
{id:35, article:'ko', image:'twe'},
{id:212, article:'ere', image:'efe'},
{id:90, article:'fefe', image:'fe'}
]
var result = data.filter(obj => obj.id == 343);
console.log(result);
result= data.find(obj => obj.id === 343);
console.log(result.id,result.article,result.image);
答案 1 :(得分:0)
使用Array.find:
const item = data.find(o => o.id === 343);