Flatten a nested array of objects over a array field

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

提交回复
热议问题