代码之家  ›  专栏  ›  技术社区  ›  Zach Smith

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

  •  1
  • Zach Smith  · 技术社区  · 8 年前

    我有这样一个数组:

     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 article ,和 image 身份证件 文章 ,和 形象 当id等于 90

    我能够识别数组,如果id存在:

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

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

    我该怎么办?任何帮助都将不胜感激。

    2 回复  |  直到 8 年前
        1
  •  1
  •   NullPointer    8 年前
    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);
    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);
        2
  •  0
  •   Evan Trimboli    8 年前

    Array.find :

    const item = data.find(o => o.id === 343);