Merge two array of objects with same keys, some object won't have the same value?

前端 未结 3 617
广开言路
广开言路 2020-12-21 01:16

I want to merge two arrays of objects. The keys are the same but the values might not always be the same.

Any solution is appreciated preferably in javascript, but

相关标签:
3条回答
  • 2020-12-21 01:42

    You could use a Map for keeping same id in the same object and Object.assign for creating independent objects.

    var g = [{ id: 36, name: 'AAA', goal: 'yes', 'random': 27 }, { id: 40, name: 'BBB', goal: 'yes' }, { id: 39, name: 'JJJ', goal: 'yes' }, { id: 27, name: 'CCC', goal: 'yes', lag: "23.3343" }],
        c = [{ id: 36, name: 'AAA', goal: 'yes', color: "purple" }, { id: 40, name: 'BBB', circle: 'yes', color: "purple" }, { id: 100, name: 'JJJ', circle: 'yes' }],
        map = new Map,
        result = g.concat(c).reduce(function (r, o) {
            var temp;
            if (map.has(o.id)) {
                Object.assign(map.get(o.id), o);
            } else {
                temp = Object.assign({}, o);
                map.set(temp.id, temp);
                r.push(temp);
            }
            return r;
        }, []);
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    Version without reduce and without concat.

    function merge(o) {
        var temp;
        if (map.has(o.id)) {
            Object.assign(map.get(o.id), o);
            return;
        }
        temp = Object.assign({}, o);
        map.set(temp.id, temp);
        result.push(temp);
    }
    
    var g = [{ id: 36, name: 'AAA', goal: 'yes', 'random': 27 }, { id: 40, name: 'BBB', goal: 'yes' }, { id: 39, name: 'JJJ', goal: 'yes' }, { id: 27, name: 'CCC', goal: 'yes', lag: "23.3343" }],
        c = [{ id: 36, name: 'AAA', goal: 'yes', color: "purple" }, { id: 40, name: 'BBB', circle: 'yes', color: "purple" }, { id: 100, name: 'JJJ', circle: 'yes' }],
        map = new Map,
        result = [];
    
    [g, c].forEach(function (a) {
        a.forEach(merge);
    });
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    0 讨论(0)
  • 2020-12-21 01:56

    Here's a Python solution. This modifies g, which you may or may not want.

    c_by_id = {d['id']: d for d in c}
    for item in g:
        item.update(c_by_id.get(item['id']), {})
    
    0 讨论(0)
  • 2020-12-21 02:04

    This can be easily achieved by underscore functions _.uniq and _.union.

    Just use this:

    var finalData = _.uniq(_.union(c, g),  function (ele)  {
                        return ele.id
                    })
    

    This will return you what you are looking for.

    0 讨论(0)
提交回复
热议问题