user5260143
user5260143

Reputation: 1098

javascript: left-merge two objects using EcmaScript 6 / immutable js

I work in javascript Project.

I'm now about search after option to merge two objects, as the second object will only ovveride fields of the first object and not add new fields which the second not has.

Something like:

const firstObj = {name:'jon', age:'6}
const secondObj = {name:'nir', mark:'100%'}

const mergedObj = leftMerge(firstObj, secondObj);

So I like mergedObj to be:

{name:'nir', age:'6'}

Is I have any way to do that with javascript (I worl with EcmaScript 6), or with immutable.js library?

Upvotes: 2

Views: 843

Answers (2)

Ori Drori
Ori Drori

Reputation: 192422

Iterate firstObj keys, and take the values from secondObj if it has those properties, if not take the values from firstObj:

const firstObj = {name:'jon', age:'6'}
const secondObj = {name:'nir', mark:'100%'}

const leftMerge = (a, b) => Object.keys(a).reduce((r, key) => (r[key] = (key in b ? b : a)[key], r), {});

const mergedObj = leftMerge(firstObj, secondObj);

console.log(mergedObj);

Upvotes: 2

Bergi
Bergi

Reputation: 665090

There's not builtin for this (Object.assign merges all properties), but you can write it really easily yourself:

function leftMerge(a, b) {
    const res = {};
    for (const p in a)
        res[p] = (p in b ? b : a)[p];
    return res;
}

Upvotes: 3

Related Questions