【问题标题】:forEach and map function to iterate through nested json arrays of objects and create a new arrayforEach 和 map 函数遍历嵌套的 json 对象数组并创建一个新数组
【发布时间】:2020-04-20 21:14:40
【问题描述】:
var res=[
      {
         "id":1,
         "type_name":"Weight",
         "type_abbr":"wt",
         "uoms":[
            {
               "id":1,
               "unit_abbr":"sh tn",
               "unit_name":"Short Tons",
               "created_at":"2017-06-07 00:35:06",
               "updated_at":"2018-05-24 23:34:25",
               "uom_type_id":1
            },
            {
               "id":3,
               "unit_abbr":"g",
               "unit_name":"Grams",
               "created_at":"2017-06-07 00:35:06",
               "updated_at":"2018-05-24 23:34:25",
               "uom_type_id":1
            }
         ]
      }
   ]

我正在尝试遍历每个结果并获取嵌套的 uoms.unit_name 并将它们注入到一个新数组中。下面是我的非工作代码。提前谢谢你。

res.forEach((uom) => {
  const uomsArr = uom.uoms.map(uoms => uoms.uoms);
});

【问题讨论】:

    标签: json multidimensional-array ecmascript-6


    【解决方案1】:

    您可以将reducemap 一起使用:

    var res = [{
        "id": 1,
        "type_name": "Weight",
        "type_abbr": "wt",
        "uoms": [{
            "id": 1,
            "unit_abbr": "sh tn",
            "unit_name": "Short Tons",
            "created_at": "2017-06-07 00:35:06",
            "updated_at": "2018-05-24 23:34:25",
            "uom_type_id": 1
          },
          {
            "id": 3,
            "unit_abbr": "g",
            "unit_name": "Grams",
            "created_at": "2017-06-07 00:35:06",
            "updated_at": "2018-05-24 23:34:25",
            "uom_type_id": 1
          }
        ]
      },
      {
        "id": 2,
        "type_name": "Weight",
        "type_abbr": "wt",
        "uoms": [{
            "id": 11,
            "unit_abbr": "sh tn",
            "unit_name": "Short Tons 2",
            "created_at": "2017-06-07 00:35:06",
            "updated_at": "2018-05-24 23:34:25",
            "uom_type_id": 11
          },
          {
            "id": 31,
            "unit_abbr": "g",
            "unit_name": "Grams 2",
            "created_at": "2017-06-07 00:35:06",
            "updated_at": "2018-05-24 23:34:25",
            "uom_type_id": 31
          }
        ]
      }
    ]
    
    console.log(res.reduce((a, r) => [...a , ...r.uoms.map(u => u.unit_name)], []))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-25
      • 2018-08-28
      相关资源
      最近更新 更多