繁体   English   中英

比较两个数组对象数据并在JavaScript中将一个对象合并为一个数组?

[英]Comparing two array objects data and merge as one object into array in javascript?

我的数组:

const create = [{"month":"Jan","createCount":"4"},{"month":"Feb","createCount":"5"}];

const close = [{"month":"Jan","closeCount":"3"},{"month":"Feb","closeCount":"5"}];

我需要合并数组对象以比较月份字段。

我想要这样的结果 ...

const data = [{"month":"Jan","createCount":"4","closeCount":"3"},{"month":"Feb","createCount":"5","closeCount":"5"}];

尝试了这段代码:

const data = [...create, ...close];

但这仅是合并两个数组数据。

请给我任何解决方案!

您可以使用.map()Object.assign()方法:

 const create = [{"month":"Jan","createCount":"4"}, {"month":"Feb","createCount":"5"}], close = [{"month":"Jan","closeCount":"3"}, {"month":"Feb","closeCount":"5"}]; const result = create.map( o => Object.assign({}, o, close.find(({month}) => month === o.month)) ); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

假设在create数组中没有在close数组中不存在的条目,反之亦然

尝试使用Array.reduceArray.mapObject.assign进行以下操作

 const create = [{"month":"Jan","createCount":"4"},{"month":"Feb","createCount":"5"}]; const close = [{"month":"Jan","closeCount":"3"},{"month":"Feb","closeCount":"5"}]; // Create an object with key as month and createCount as value let obj = create.reduce((a, o) => Object.assign(a, {[o.month]: o.createCount}), {}); // Iterate over close array and add createCount from obj let result = close.map(o => ({...o, createCount : obj[o.month]})); console.log(result); 

简单地用于

const create = [{ "month": "Jan", "createCount": "4" }, { "month": "Feb", "createCount": "5" }];
const close = [{ "month": "Jan", "closeCount": "3" }, { "month": "Feb", "closeCount": "5" }];
for (var i in create) {
    var item = create[i];
    item.closeCount = close.find(x => x.month == item.month).closeCount;
}
console.log(create);

在这里我添加了一些示例,请参考该代码

 const create = [{"month":"Jan","createCount":"4"},{"month":"Feb","createCount":"5"}]; const close = [{"month":"Jan","closeCount":"3"},{"month":"Feb","closeCount":"5"}]; console.log(create.length); for(var data = 0 ; data < create.length ; data++){ var datas = [] if(create[data].month == close[data].month){ datas=Object.assign(create[data],close[data]);console.log(create[data]); } } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM