how to concatenate two object and replace the values?

Viewed 220

I'm trying to concatenate two objects. I need to merge the two object and based on the "beforeVist" object value within the arrow.

My two objects down below:

const beforeVist = {
  name : '<<name>>',
  age : '<<age>>',
  place : '<<place>>'
};

const afterVist = {
  name : 'Robin',
  age : 22,
  place : 'Mars'
}

var Updated = {...afterVist, ...beforeVist};
console.log(Updated)

when I'm trying do console.log() function output below,

{
    name : 'Robin',
    age : 22,
    place : 'Mars'
}

this is what my expected output is. I'm not sure that it is the right way.

Thanks advance!!!

3 Answers

It is the right way. You should use object sprad

let merged = {...obj1, ...obj2};

Method for ES5 and Earlier

for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }

Because << >> are always at the first two places and the last two places we can simply slice and then reassign the value.

const beforeVist = {
    name: '<<name>>',
    age: '<<age>>',
    place: '<<place>>'
};

const afterVist = {
    name: '<<Robin>>',
    age: '<<22>>',
    place: '<<Mars>>'
}

var Updated = {...beforeVist, ...afterVist };

Object.entries(Updated).forEach(([key, value]) => {

    let val = value.slice(2, value.length - 2);
    Updated[key] = val;
})


console.log(Updated)

At the moment you are just overwriting the properties from afterVist with the properties in beforeVist, and since the property names are the same, you're essentially just making a shallow copy. This is more evident if your afterVist has different property names to beforeVist (and why I've provided different property names in beforeVist below - to show that they don't have to be the same and that the value is grabbed based on the key specified in <<key>>)

Instead, you can use Object.fromEntries() by mapping the Object.entries() of your original object, and using replace on the keys to extract the key name like so:

const beforeVist = { myName: '<<name>>', myAge: '<<age>>', myPlace: '<<place>>' }; 
const afterVist = { name: 'Robin', age: 22, place: 'Mars' };

const result = Object.fromEntries(Object.entries(beforeVist).map(([key, value]) => [
  key,
  value.replace(/<<([^>>]*)>>/, (_, g) => afterVist[g])
]));
console.log(result);

You could also use Object.assign

const a = {p1: 12, p2: 23}
const b = {p2: 34, p3: 'adfa'}
let c = Object.assign(b, a)
// c contains:
{p2: 23, p3: "adfa", p1: 12}

If you care about immutability, you can provide separate "result" object:

const res = Object.assign({}, b, a)

// a and b still hold the original values

NOTE: properties ORDER will be driven from left-to-right ("p2" is the first prop in B, but second in A), but the VALUES from right-to-left(result.p2 contains value from the rightMost object with such property - ie A.p2 overrides B.p2

Related