检索键等于值的javascript数组对象数据

时间:2018-09-23 02:06:30

标签: javascript arrays

我有一个这样的数组:

 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等于某个数字的idarticleimage数据。因此,例如,我想在id等于id时抓取articleimage90

我能够辨别该数组以及该id是否存在:

data.forEach(function(key,value){
            if (key['id'] === 343) {
                //how to grab rest of this object?
            }
        })

但是从那里我不知道如何获取其余的对象数据。

我将如何处理?任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

  1. 您快到了。根据valueobject获取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);

  1. 您也可以使用Array.propotype.filter()Array.prototype.find()

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);