【问题标题】:Fetch inner object array from object array - javascript从对象数组中获取内部对象数组 - javascript
【发布时间】:2021-08-22 11:11:30
【问题描述】:

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

data = [
  {
    "field": "A",
    "items": [
      {
        "Id": 001,
        "ItemDescription": "item 1"
      }
    ]
  },
  {
    "field": "A",
    "items": [
      {
        "Id": 002,
        "ItemDescription": "item 2"
      },
      {
        "Id": 003,
        "ItemDescription": "item 3"
      },
      {
        "Id": 004,
        "ItemDescription": "item 4"
      }
    ]
  }
]

我试图从对象数组中仅获取内部对象数组。

我尝试了不同的方法从对象数组中获取内部对象数组,

data.map((u,i) => u[i].map((a,b)=> a.items))

预期结果:

data = [
      {
        "Id": 001,
        "ItemDescription": "item 1"
      },
      {
        "Id": 002,
        "ItemDescription": "item 2"
      },
      {
        "Id": 003,
        "ItemDescription": "item 3"
      },
      {
        "Id": 004,
        "ItemDescription": "item 4"
    
      }
    ]

【问题讨论】:

    标签: javascript arrays json multidimensional-array


    【解决方案1】:

    您可以使用mapflat

    let data = [
      {
        "field": "A",
        "items": [
          {
            "Id": 001,
            "ItemDescription": "item 1"
          }
        ]
      },
      {
        "field": "A",
        "items": [
          {
            "Id": 002,
            "ItemDescription": "item 2"
          },
          {
            "Id": 003,
            "ItemDescription": "item 3"
          },
          {
            "Id": 004,
            "ItemDescription": "item 4"
          }
        ]
      }
    ]
    
    let result = data.map(d => d.items).flat();
    
    console.log(result);

    输出

    【讨论】:

    • 否定。不符合我的预期结果。上面的代码导致我低于 json 数组。 [ [ { "Id": 001, "ItemDescription": "eeeee" } ], [ { "Id": 002, "ItemDescription": "23434" }, { "Id": 003, "ItemDescription": "12342" }, { "Id": 004, "ItemDescription": "type B" } ] ]
    • 它应该可以工作。请检查控制台中的 codepen 输出。 codepen.io/debraj1983/pen/YzZadRr?editors=0010
    • 问题本身已经提到了预期的结果。我需要单个数组对象中的 001 到 004 项。
    • meta.stackoverflow.com/a/356679/14032355 ,你可以把你的js代码留在代码sn-p中
    • @ikhvjs 这太棒了。谢谢。
    【解决方案2】:

    只需使用单个.map 即可获取项目array 中的值

    let newArr = data.map((u,i) => u.items)
    console.log(newArr)
    

    如果要返回单个数组中的所有值,请使用.flat

    console.log(newArr.flat())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-18
      • 1970-01-01
      • 2020-07-14
      • 2021-06-02
      • 1970-01-01
      • 2023-01-05
      • 2019-11-10
      • 2016-08-29
      相关资源
      最近更新 更多