简体   繁体   English

将嵌套的 object 检索到 es6 或 lodash 中的数组中

[英]Retrieve nested object into array in es6 or lodash

I am trying to extract nested objects of same keys into an array from array of objects.我正在尝试将相同键的嵌套对象从对象数组中提取到数组中。

Example:例子:

There is an array as shown below:有一个数组,如下图:

[
 {
  id:1,
  model:'car',
  manufacturer:{
   id:1,
   name:'benz',
   year:2010
  }
 },
 {
  id:1,
  model:'car',
  manufacturer:{
   id:2,
   name:'benz',
   year:2012
  }
 },
 {
  id:2,
  model:'bus',
  manufacturer:{
   id:3,
   name:'volvo',
   year:2020
  }
 }
]

I need the result as shown below:我需要如下所示的结果:

[
 {
   id:1,
   model:'car',
   manufacturer:[
    {
     id:1,
     name:'benz',
     year:2010
    },
    {
     id:2,
     name:'benz',
     year:2012
    }
   ]
 },
 {
  id:2,
  model:'bus',
  manufacturer:{
   id:3,
   name:'volvo',
   year:2020
  }
 }
]

How to achieve this?如何做到这一点? I tried all the possible ways using lodash but unable to get desired result.我使用 lodash 尝试了所有可能的方法,但无法获得所需的结果。 Please help me.请帮我。 Thank you.谢谢你。

 let data =[ { id:1, model:'car', manufacturer:{ id:1, name:'benz', year:2010 } }, { id:1, model:'car', manufacturer:{ id:2, name:'benz', year:2012 } }, { id:2, model:'bus', manufacturer:{ id:3, name:'volvo', year:2020 } } ] let temp=[]; for(var i=0;i<=data.length-1;i++){ let pos = temp.findIndex(el=>el.id==data[i]['id']); if(pos == -1){ temp.push(data[i]); }else{ let obj = temp[pos]['manufacturer']; temp[pos]['manufacturer'] = Array.isArray(obj)? [...obj,data[i]['manufacturer']]: [obj,data[i]['manufacturer']] } } console.log(temp)

You can do with simple for loops您可以使用简单的 for 循环

for(let i=0;i<arr.length;i++)) {
// check required key matching
// append to new array
}

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

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