首页 > 解决方案 > 根据属性值从对象数组中获取值

问题描述

我有一个对象数组,如下所示:

   Identifiers: [
     {
     Identifier: {
      Source: "TEST",
      Symbol: "123456",
     }
    },
     {
      Identifier: {
       Source: "TEST2",
       Symbol: "345678"
      }
    },
    {
      Identifier: {
       Source: "TEST3",
       Symbol: "456789"
     }
   ]

我需要从数组中检索 Source: "TEST3" 的 Symbol 键的值。我只能访问 TEST3。检索 val 的最佳方法是什么

标签: javascriptarraysobjectecmascript-6lodash

解决方案


您可以像这样使用find解构返回的Identifier对象:

let input = [{Identifier:{Source:"TEST",Symbol:"123456",}},{Identifier:{Source:"TEST2",Symbol:"345678"}},{Identifier:{Source:"TEST3",Symbol:"456789"}}]
   
let { Identifier: { Symbol } } = input.find(a => a.Identifier.Source === "TEST3");
console.log(Symbol)

如果 a 的标识符可能不存在Source,请使用默认值

let { Identifier: { Symbol } = {} } = input.find(a => a.Identifier.Source === "TEST333") || {};

如果您不想使用解构:

let input = [{Identifier:{Source:"TEST",Symbol:"123456",}},{Identifier:{Source:"TEST2",Symbol:"345678"}},{Identifier:{Source:"TEST3",Symbol:"456789"}}]

let found = input.find(a => a.Identifier.Source === "TEST3");
let source = found && found.Identifier.Source;

console.log(source)


推荐阅读