[英]How can I merge two array of objects and concatenate values?
I have this two array of objects 我有这两个对象数组
var client = [{
"creazione": "1970-01-01",
"value": 2
}, {
"creazione": "2014-03-12",
"value": 4
}, {
"creazione": "2014-03-14",
"value": 1
}],
order = [{
"creazione": "1970-01-01",
"value": 1
}, {
"creazione": "2014-03-13",
"value": 5
}, {
"creazione": "2014-03-14",
"value": 1
}];
I need to merge these two arrays to get something like: 我需要合并这两个数组来得到类似的东西:
[{
x: '1970-01-01',
y: [2, 1]
}, {
x: '2014-03-12',
y: [4, 0]
}, {
x: '2014-03-14',
y: [1, 1]
}, {
x: '2014-03-13',
y: [0, 5]
}]
In few words I need to check if a.creazione == b.creazione
then merge the key and concat the values in an array (first line of result), else if it is different, assign the value of the existing array in the right position of the y
array (third line of result). 简而言之,我需要检查a.creazione == b.creazione
然后合并密钥并将数值连接到数组(结果的第一行),否则如果它不同,则在右边分配现有数组的值y
数组的位置(结果的第三行)。
PS: I need to get this structure beacuse I'm using Angular-Charts library, and it ask for data in this uncomfortable way. PS:我需要得到这个结构,因为我正在使用Angular-Charts库,它以这种不舒服的方式询问数据。
Any idea on how to achieve this? 有关如何实现这一点的任何想法?
Allow me to amuse you with the power of functional programming :) 请允许我用函数编程的力量来娱乐你:)
client = _.object(_.map(client, _.values));
order = _.object(_.map(order , _.values));
var result = _
.chain(_.keys(client))
.union(_.keys(order))
.map(function (key) {
return [key, [client[key] || 0, order[key] || 0]];
})
.map(_.partial(_.zipObject, ['x', 'y']))
.value();
console.log(result);
# [ { x: '1970-01-01', y: [ 2, 1 ] },
# { x: '2014-03-12', y: [ 4, 0 ] },
# { x: '2014-03-14', y: [ 1, 1 ] },
# { x: '2014-03-13', y: [ 0, 5 ] } ]
Using plain JavaScript: 使用纯JavaScript:
var result = [];
client.forEach( function( entry ) {
for( var i = 0; i < order.length; ++i ) {
if( entry.creazione === order[i].creazione ) {
result.push( { x: entry.creazione, y: [ entry.value, order[i].value ] } );
order.splice( i, 1 );
return;
}
}
result.push( { x: entry.creazione, y: [ entry.value, 0 ] } );
} );
order.forEach( function( entry ) {
result.push( { x: entry.creazione, y: [ 0, entry.value ] } );
} );
Fiddle: http://jsfiddle.net/rPk6e/ 小提琴: http : //jsfiddle.net/rPk6e/
Note that for simplicity the order array is modified. 请注意,为简单起见,修改了顺序数组。 If that is a problem for your use case simply make a copy using slice. 如果这是您的用例的问题,只需使用切片进行复制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.