Javascript合并属于对象中不同键的数组值

时间:2016-10-15 13:36:15

标签: javascript arrays lodash

我有一个这样的对象:

data = {
    0: [{name: 'ABC', age: '43'}, {name: 'DEF', age: '20'}],
    1: [{name: 'GHI', age: '41'}, {name: 'JKL', age: '25'}],
    2: [{name: 'MNO', age: '19'}, {name: 'PQR', age: '24'}]
};

我想合并键的数组值,并创建一个像这样的对象数组:

[ {name: 'ABC', age: '43'}, {name: 'DEF', age: '20'}, {name: 'GHI', age: '41'}, {name: 'JKL', age: '25'}, {name: 'MNO', age: '19'}, {name: 'PQR', age: '24'} ]

我通过Lodash docs找到了一些东西,但却找不到合适的组合。有没有人知道如何以简洁的方式,Lodash(最好),或其他什么?在此先感谢!!

5 个答案:

答案 0 :(得分:2)

使用_.values()提取数组,并将concat应用于数组:



var data = {
    0: [{name: 'ABC', age: '43'}, {name: 'DEF', age: '20'}],
    1: [{name: 'GHI', age: '41'}, {name: 'JKL', age: '25'}],
    2: [{name: 'MNO', age: '19'}, {name: 'PQR', age: '24'}]
};

var result = Array.prototype.concat.apply([], _.values(data));
    
console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

没有lodash,只是简单的旧JS:

var data = {
    0: [{name: 'ABC', age: '43'}, {name: 'DEF', age: '20'}],
    1: [{name: 'GHI', age: '41'}, {name: 'JKL', age: '25'}],
    2: [{name: 'MNO', age: '19'}, {name: 'PQR', age: '24'}]
};

var result = [];
for (var key in data) {
    if (data.hasOwnProperty(key)) {
        result = result.concat(data[key]);
    }
}
console.log(result);

答案 2 :(得分:1)

您只需将数组(如对象)转换为array,然后将其展平即可。

data = {
    0: [{name: 'ABC', age: '43'}, {name: 'DEF', age: '20'}],
    1: [{name: 'GHI', age: '41'}, {name: 'JKL', age: '25'}],
    2: [{name: 'MNO', age: '19'}, {name: 'PQR', age: '24'}]
};

console.log(
  _.flatten(_.toArray(data))
)
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>

答案 3 :(得分:1)

使用新的Object.values(),您可以在纯JS ES6中执行以下操作;

var data = { 0: [{name: 'ABC', age: '43'}, {name: 'DEF', age: '20'}],
             1: [{name: 'GHI', age: '41'}, {name: 'JKL', age: '25'}],
             2: [{name: 'MNO', age: '19'}, {name: 'PQR', age: '24'}]
           },
 newData = [].concat(...Object.values(data));
console.log(newData);

答案 4 :(得分:1)

这是另一个纯粹的javascript版本。

var data = {
    0: [{name: 'ABC', age: '43'}, {name: 'DEF', age: '20'}],
    1: [{name: 'GHI', age: '41'}, {name: 'JKL', age: '25'}],
    2: [{name: 'MNO', age: '19'}, {name: 'PQR', age: '24'}]
};

var newdata = Object.keys(data).reduce(function (a,b) { 
  return a.concat(data[b]);
}, []);

console.log(newdata);