在数组字段上展平嵌套的对象数组

时间:2016-10-25 21:34:22

标签: javascript angularjs underscore.js lodash

有一个对象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'}]]

期望的输出:

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

请建议!我试图用lodash / underscore完成这个。

3 个答案:

答案 0 :(得分:1)

将原始数组中的每个项目映射到一个新数组,根据addr字段的数量包含多个项目。使用concat将所有内容展平为一个新数组。

如果您正在使用babel或类似内容转换为ES5,则可以使用Object.assign()创建新项目,因为IE不支持此项目。但是,由于您使用了角度,因此可以使用angular.extend代替。

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>
&#13;
&#13;
&#13;

ES6:

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以迭代数组和内部数组以构建想要的结果。

&#13;
&#13;
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);
&#13;
&#13;
&#13;

ES6

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以使用reduce()forEach()Object.assign()返回所需的结果。

&#13;
&#13;
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)
&#13;
&#13;
&#13;