【问题标题】:get value from an array of objects based on value of attribute根据属性值从对象数组中获取值
【发布时间】:2019-08-12 10:54:45
【问题描述】:

我有一个对象数组如下:

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

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

【问题讨论】:

  • 使用find()方法获取对象
  • Identifiers.find(el => el['Identifier']['Source'] === 'TEST3')['Identifier']['Symbol'] 使用 find 是最好的,只是要小心你的键选择。

标签: javascript arrays object ecmascript-6 lodash


【解决方案1】:

您可以使用finddestructure 以这样的方式返回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)

如果Source 的标识符可能不存在,请使用default value

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)

【讨论】:

    【解决方案2】:

    使用lodash's_.flow()_.partialRight()创建一个函数,使用_.find()通过Source属性获取对象,然后使用_.get()提取Symbol_.get()将如果找不到该项目,则返回undefined)。

    const { flow, partialRight: pr, find, get } = _
    
    const symbolBySource = src => flow(
      pr(find, ['Identifier.Source', src]),
      pr(get, 'Identifier.Symbol')
    )
    
    const identifiers = [{Identifier:{Source:"TEST",Symbol:"123456",}},{Identifier:{Source:"TEST2",Symbol:"345678"}},{Identifier:{Source:"TEST3",Symbol:"456789"}}]
    
    const result = symbolBySource('TEST3')(identifiers)
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

    还有更简洁的lodash/fp 版本:

    const { flow, find, get } = _
    
    const symbolBySource = src => flow(
      find(['Identifier.Source', src]),
      get('Identifier.Symbol')
    )
    
    const identifiers = [{Identifier:{Source:"TEST",Symbol:"123456",}},{Identifier:{Source:"TEST2",Symbol:"345678"}},{Identifier:{Source:"TEST3",Symbol:"456789"}}]
    
    const result = symbolBySource('TEST3')(identifiers)
    
    console.log(result)
    <script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-23
      • 1970-01-01
      • 1970-01-01
      • 2015-04-05
      • 2020-04-28
      • 1970-01-01
      • 1970-01-01
      • 2021-11-07
      相关资源
      最近更新 更多