根据属性值从对象数组中获取值

时间:2019-03-21 14:37:14

标签: javascript arrays object ecmascript-6 lodash

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

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

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

2 个答案:

答案 0 :(得分:3)

您可以使用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)

答案 1 :(得分:1)

使用lodash's _.flow()_.partialRight()创建一个函数,该函数使用_.find()通过Source属性获取对象,然后提取{{ 1}}使用Symbol(如果找不到该项目,_.get()将返回_.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)

以及更短的lodash/fp版本:

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
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)