Flatten a nested array of objects over a array field

后端 未结 3 1518
面向向阳花
面向向阳花 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)

    0 讨论(0)
  • 2021-01-28 17:51

    Map every item in the original array to a new array, with a number of items according to the number of addr fields. Using concat flatten everything to a new array.

    You can create new items using Object.assign() if you're transpiling to ES5 with babel or similar, as it's not supported by IE. However, since you're using angular, you can use angular.extend instead.

    ES5:

    var arr = [
      {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 = [].concat.apply([], arr.map(function(item) {     
      return item.addr.map(function(addr) {
        return angular.extend({}, item, { addr: addr });
      });
    }));
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>

    ES6:

    const arr = [
      {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'}]}
    ];
       
    const result = [].concat(...arr.map((item) => item.addr.map((addr) => Object.assign({}, item, { addr }))));
    
    console.log(result);

    0 讨论(0)
  • 2021-01-28 17:54

    You could iterate the array and the inner array for building the wanted result.

    var array = [{ 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' }] }],
        result = array.reduce(function (r, a) {
            return r.concat(a.addr.map(function (b) {
                return { name: a.name, age: a.age, addr: b };
            }));
        }, []);
    
    console.log(result);

    ES6

    var array = [{ 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' }] }],
        result = array.reduce((r, a) => r.concat(a.addr.map(b => ({ name: a.name, age: a.age, addr: b }))), []);
    
    console.log(result);

    0 讨论(0)
提交回复
热议问题