Flatten a nested array of objects over a array field

后端 未结 3 1521
面向向阳花
面向向阳花 2021-01-28 17:23

Have an object a1 =

[{name:\'x\',age:21, addr:[{flat:1,add:\'xyz\'},{flat:2,add:\'xsr\'}]},
{name:\'y\',age:22, addr:[{flat:3,add:\'xyz1\'},{flat:4,add:\'xsr1\'}         


        
3条回答
  •  滥情空心
    2021-01-28 17:48

    You can use reduce(), forEach() and Object.assign() to return desired result.

    var data = [{name:'x',age:21, addr:[{flat:1,add:'xyz'},{flat:2,add:'xsr'}]},
    {name:'y',age:22, addr:[{flat:3,add:'xyz1'},{flat:4,add:'xsr1'}]}];
    
    var result = data.reduce(function(r, o) {
      o.addr.forEach(function(e) {
        r.push(Object.assign({name: o.name, age: o.age}, e));
      })
      return r;
    }, []);
    
    console.log(result)

提交回复
热议问题