【问题标题】:How to find an attribute value in an array of objects that are each an array of objects that is coming from an API response [duplicate]如何在对象数组中查找属性值,每个对象数组都是来自 API 响应的对象数组 [重复]
【发布时间】:2021-11-20 22:39:51
【问题描述】:

假设我有以下未命名对象数组,每个对象都是命名对象数组:

[{id: 123, name: 'Foo', code: 'ABC123', enabled: true},{id: 124, name: 'Bar', code: '123ABC', enabled: true}]

此数据已从 API 调用响应转换为对象数组,因此未定义任何命名对象。例如,我无法使用以下方式检查任何对象的name

for (let i = 0; i < resp.length; i++){
    if(resp[i].name = key){do something}
}

(即以下问题的解决方案:Find a value in an array of objects in Javascript)因为 name 对于相应的对象未定义。

我有办法访问那个对象的那个属性吗?

【问题讨论】:

    标签: javascript arrays typescript object data-structures


    【解决方案1】:

    我只是使用你的代码,但略有改变。主要错误是您在 if 语句 (=) 中分配了一个变量,而不是比较 (==)。

    您还需要在该键的值中添加一个键和一个匹配的单词:resp[i][key] == match

    const apiResponseArr = [{id: 123, name: 'Foo', code: 'ABC123', enabled: true},{id: 124, name: 'Bar', code: '123ABC', enabled: true}];
    
    
    function find(resp, match, key) {
      key = key || 'name';
      
      for (let i = 0; i < resp.length; i++){
        if(resp[i][key] == match) { return resp[i]; }
      }
    
      return 'not found';
    }
    
    console.log( find(apiResponseArr, 'Bar') ); // [object]
    console.log( find(apiResponseArr, 'Zzz') ); // 'not found'
    
    console.log( find(apiResponseArr, 'ABC123', 'code') ); // [object]

    在您的链接线程中,you got a suggestion 以更短的方式编写它:

    const apiResponseArr = [{id: 123, name: 'Foo', code: 'ABC123', enabled: true},{id: 124, name: 'Bar', code: '123ABC', enabled: true}];
    
    
    function find(resp, match, key = 'name') {
      return resp.find(x => x[key] === match);
    }
    
    console.log( find(apiResponseArr, 'Bar') ); // [object]
    console.log( find(apiResponseArr, 'Zzz') ); // undefined
    
    console.log( find(apiResponseArr, 'ABC123', 'code') ); // [object]

    【讨论】:

      猜你喜欢
      • 2018-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-17
      • 2021-11-16
      • 2021-05-29
      • 1970-01-01
      相关资源
      最近更新 更多