【问题标题】:Retrieving values from array in angular以角度从数组中检索值
【发布时间】:2020-08-21 14:00:43
【问题描述】:

我正在开发一个角度应用程序。我有一个数组如下。

[
    { 
     Code: "123",
     Details:[
       {
        Id: "1",
        Name: "Gary"
       },
       {
        Id: "2",
        Name: "Rocky"
       }]
    },
    { 
     Code: "456",
     Details:[
       {
        Id: "3",
        Name: "Cindy"
       },
       {
        Id: "4",
        Name: "Jacky"
       }]
    }
]

可以有更多的元素。此数组包含代码、详细信息数组(可以是任意长度)- 此详细信息数组包含 ID 和名称。我有来自查询参数的 ID。我需要在 Details 数组中查看 Id 匹配的 id 并获取代码。例如,如果来自查询参数的 Id 是 4,那么我需要检索 Code 值,即 456。如果 Id 值是 2,那么我需要检索 Code 值,即 123。我该怎么做?

【问题讨论】:

  • 不是数组
  • let {Code} = (arr.find(({Details}) => Details.some(({Id}) => Id === 4)) || {}); //If not found, undefined will be assigned
  • @Ele 它在​​哪里提供代码
  • @Lozy 对找到的对象进行解构赋值。

标签: javascript angular typescript angular8


【解决方案1】:

假设 OP 正在处理一组对象。

您可以使用函数Array.prototype.find 和函数Array.prototype.some 来识别特定细节。

最后,使用解构赋值我们可以提取属性Code

let arr = [{
  Code: "123",
  Details: [{
    Id: "1",
    Name: "Gary"
  }, {
    Id: "2",
    Name: "Rocky"
  }]
}, {
  Code: "456",
  Details: [{
    Id: "3",
    Name: "Cindy"
  }, {
    Id: "4",
    Name: "Jacky"
  }]
}];
let { Code } = arr.find(({ Details }) =>
Details.some(({ Id }) => Id === "4")) || {}; //If not found, undefined will be assigned

console.log(Code);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-27
    • 2012-01-28
    • 2018-06-14
    • 2017-07-20
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    相关资源
    最近更新 更多