[英]create array of values with same key from an array of objects
我有一个看起来像这样的对象数组:
[
{
key1: val_1.a
key2: val_2.a
key3: val_3.a
},{
key1: val_1.b
key2: val_2.b
key3: val_3.b
},{
key1: val_1.c
key2: val_2.c
key3: val_3.c
}
]
我想使用该对象创建另一个如下所示的对象:
{
key1: [val_1.a, val_1.b, val_1.c]
key2: [val_2.a, val_2.b, val_2.c]
key3: [[val_3.a, val_3.b, val_3.c]
}
由于每个对象中的键都是相同的,因此我只想将与每个键对应的所有值保存在数组中。
拜托,如果有人以前必须这样做并且可以共享代码,那就太好了。 提前致谢。
您可以这样进行操作,使其在所有浏览器中都可以使用,甚至在所有对象都不具有完全相同的键集的情况下也可以使用(例如,它将只为存在的任何键积累数据):
function combineKeyData(data) {
var output = {}, item;
// iterate the outer array to look at each item in that array
for (var i = 0; i < data.length; i++) {
item = data[i];
// iterate each key on the object
for (var prop in item) {
if (item.hasOwnProperty(prop)) {
// if this keys doesn't exist in the output object, add it
if (!(prop in output)) {
output[prop] = [];
}
// add data onto the end of the key's array
output[prop].push(item[prop]);
}
}
}
return output;
}
工作的jsFiddle: http : //jsfiddle.net/jfriend00/0jjquju9/
说明:
result = {};
for (var i = 0; i < array.length; i++) {
var obj = array[i];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (result[key]) {
result[key].push(obj[key]);
} else {
retult[key] = [obj[key]];
}
}
}
}
var arr = [ { key1: 'val_1.a', key2: 'val_2.a', key3: 'val_3.a' },{ key1: 'val_1.b', key2: 'val_2.b', key3: 'val_3.b' },{ key1: 'val_1.c', key2: 'val_2.c', key3: 'val_3.c' } ] var result = arr.reduce(function(obj, current) { //Reduce the array to an object Object.keys(current).forEach(function(key) { //Each key obj[key] = obj[key] || []; //Has to be an array if not exists obj[key] = Array.isArray(obj[key]) ? obj[key] : [obj[key]]; //Has to be an array if not an array obj[key].push(current[key]); //Add current item to array of matching key }); return obj; //Continue to the next object in the array }); console.log(result);
以上功能: Array#reduce
, Array#forEach
, Array.isArray
, Object.keys
都是ECMAScript 5规范的一部分,因此,它们在IE8及以下版本中不可用。
let R = require('ramda');
let arr =[
{
'key1': 'a',
'key2': 'b',
'key3': 'c',
},{
'key1': 'a1',
'key2': 'b1',
'key3': 'c1',
},{
'key1': 'a2',
'key2': 'b2',
'key3': 'c2',
}
];
let key1 = R.pluck('key1', arr);
let key2 = R.pluck('key2', arr);
let key3 = R.pluck('key3', arr);
let obj = {
key1,
key2,
key3
};
Obj = { key1: [ 'a', 'a1', 'a2' ], key2: [ 'b', 'b1', 'b2' ], key3: [ 'c', 'c1', 'c2' ] }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.