简体   繁体   中英

Merge Objects: Problem with comparing and merge two objects in javascript

Good night. Some charitable soul to help me with a problem about javascript objects. Thank you very much who can...

var arrA = [
    {language:'php', count_access:5},
    {language:'c', count_access:7}
];

var arrB = [
    {language:'php', count_access:0},
    {language:'c', count_access:0},
    {language:'python', count_access:0},
    {language:'ace', count_access:0},
    {language:'electron', count_access:0},
];

var result = [...arrA, ...arrB].reduce((acc, item) => { 
    return item;
 }) ;

arrA.concat(result)

//How would you do for the output to be

/*[
{language:'php', count_access:5},
{language:'c', count_access:7},
{language:'python', count_access:0},
{language:'ace', count_access:0},
{language:'electron', count_access:0},
]*/

This will work, it also adds up the counts for matching language

 var arrA = [ {language:'php', count:5}, {language:'c', count:7} ]; var arrB = [ {language:'php', count:0}, {language:'c', count:0}, {language:'python', count:0}, {language:'ace', count:0}, {language:'electron', count:0}, ]; let result = [...arrA, ...arrB].reduce((acc, item) => { let found = acc.find(x => x.language=== item.language); if (found) { found.count += item.count; } else { acc.push(Object.assign({},item)); } return acc; }, []) console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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