javascript - 根据属性值从对象数组中获取值
问题描述
我有一个对象数组,如下所示:
Identifiers: [
{
Identifier: {
Source: "TEST",
Symbol: "123456",
}
},
{
Identifier: {
Source: "TEST2",
Symbol: "345678"
}
},
{
Identifier: {
Source: "TEST3",
Symbol: "456789"
}
]
我需要从数组中检索 Source: "TEST3" 的 Symbol 键的值。我只能访问 TEST3。检索 val 的最佳方法是什么
解决方案
您可以像这样使用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)
推荐阅读
- angular - 如何更改 ng2 智能表列宽?
- vba - 如果单元格包含除数字以外的任何内容,我需要显示一个 msgbox 并退出 sub。现在它给出了一个空白
- python - Django `python manage.py runserver` 不支持 asyncio&aiohttp
- reactjs - 将 React Web 应用程序迁移到 Electron
- c# - SQL Server - 重复键错误
- peg - 具有任意数量限定符的 PEG 解析声明
- azure - 基于 deviceids 触发 azure 函数
- javascript - 使用 Knockout 从 JSON 编写列表元素
- ios - 快速:滚动集合视图
- elasticsearch - 如何查询具有多个条件的字符串?