代码之家  ›  专栏  ›  技术社区  ›  Alfred Balle

从对象数组中获取密钥/id

  •  -5
  • Alfred Balle  · 技术社区  · 6 年前

    在JavaScript中,我有以下代码来查找数组中的特定对象:

    records.find(function (obj) { return obj.time === tmp_date; })
    

    是否可以从数组中获取对象的key/id records ?

    2 回复  |  直到 6 年前
        1
  •  -1
  •   Jeremy Thille    6 年前

    假设 records 看起来像这样(因为你没有提供):

    let records = [
      {
         id : 1,
         time : 10
      },
      {
         id : 2,
         time : 20
      }
    ]
    

    然后,您可以通过以下方式简单地获取匹配对象的索引:

     let records = [
          {
             id : 1,
             time : 10
          },
          {
             id : 2,
             time : 20
          }
        ],
        tmp_date = 20,
        index;
        
    for(let i in records){
      if(records[i].time===tmp_date){
        index = i;
        break;
      }
    }
    
    console.log(`Found time ${tmp_date} at index ${index}.`)
        2
  •  -1
  •   Rohit Agrawal    6 年前

    find() 方法将根据条件返回第一个匹配对象。然后你可以把 id 就像我们访问其他属性一样。

    var records = [{time:10, id:1}, {time:20, id:2}, {time:30, id:3}];
    
    var id = records.find(function (obj) { return obj.time === 20; }).id;
    
    console.log(id);