简体   繁体   English

Lodash从嵌套对象中提取值

[英]Lodash extract value from nested object

I have below object which I am currently looping through to get item value. 我下面有一个对象,该对象当前正在循环以获取项目值。 Currently I am using lodash _.forEach to achieve this. 目前,我正在使用lodash _.forEach实现此目的。 I am not sure what is best possible to create a new object with item name as key and value as value. 我不确定以项目名称作为键并将值作为值创建新对象的最佳方法。

data =  [
  {
     "panels" : [
        {
          "title": "Panel 1",
          "items" : [
              {
                 "name": item1,
                 "value": 1
              }
              {
                 "name": item2,
                 "value": 2
              }
           ]
         },
         {
            "title": "Panel 2",
             "items" : [
              {
                 "name": item3,
                 "value": 3
              }
              {
                 "name": item4,
                 "value": 5
              }
           ]
         }
     ]
  }

  {
     "panels" : [
        {
          "title": "Panel 3"
          "items" : [
              {
                 "name": item5,
                 "value": 5
              }
              {
                 "name": item6,
                 "value": 6
              }
           ]
        }
     ]
  }  
]

  let values = [];
    _.forEach(data, (groups) => {
        _.forEach(groups.panels, (panel) => {
            _.forEach(panel.items, (item) => {
                  values[item.name] = item.value;                   
            });
        });
    });
    return values;

Is there any other way I can achieve this in more efficient way ? 我还有其他方法可以更有效地实现这一目标吗?

You could use a nested for...of loops with destructuring 您可以使用嵌套的for...of循环进行解构

 const data=[{panels:[{title:"Panel 1",items:[{name:"item1",value:1},{name:"item2",value:2}]},{title:"Panel 2",items:[{name:"item3",value:3},{name:"item4",value:5}]}]},{panels:[{title:"Panel 3",items:[{name:"item5",value:5},{name:"item6",value:6}]}]}]; const output = {}; for (const { panels } of data) for (const { items } of panels) for (const { name, value } of items) output[name] = value; console.log(output) 

Or, 要么,

You could use a chained flatMap to get an array of items. 您可以使用链接的flatMap获取项目数组。 Then reduce the items array to get an object with name as key and value as it's value 然后reduce items数组以获得name为键, value的对象

 const data=[{panels:[{title:"Panel 1",items:[{name:"item1",value:1},{name:"item2",value:2}]},{title:"Panel 2",items:[{name:"item3",value:3},{name:"item4",value:5}]}]},{panels:[{title:"Panel 3",items:[{name:"item5",value:5},{name:"item6",value:6}]}]}]; const output = data.flatMap(o => o.panels) .flatMap(p => p.items) .reduce((acc, o) => ({ ...acc, [o.name]: o.value }), {}) console.log(output) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM