AConsumer
AConsumer

Reputation: 2801

Object spread not giving desired results

let me={
    name:"Shivendra",
    age:21
}


let you={
    name:"Neha",
    age:22
}


let mergeMeAndYou={
    ...me, ...you
}

console.log(mergeMeAndYou);

I am getting the output:- { name: 'Neha', age: 22 }

Now I was not expecting this. Can any one explain this result ? & how I will now get the merged object ? I am using node version 8.9.4.

Upvotes: 0

Views: 45

Answers (4)

Eddie
Eddie

Reputation: 26854

You can do this by enclosing the object with { and }, like: {...obj}

let me={
   name:"Shivendra",
   age:21
}


let you={
   name:"Neha",
   age:22
}

//Putting the me and you on an array.
let mergeMeAndYou = [
   {...me},{ ...you}
]

console.log(mergeMeAndYou);

//Putting the me and you on an object.	
let mergeMeAndYou2 = {
   me:{...me}, you:{ ...you}
}

console.log(mergeMeAndYou2);

Note: Based on how you want to combine the objects, you don't really need to Spread the objects. You can just:

let mergeMeAndYou = [me,you];

let mergeMeAndYou2 = {me:me, you:you}

Upvotes: 2

user7125259
user7125259

Reputation:

I think you're misunderstanding what the object spread does. It lists the properties of each object into a new object. Where you do it with more than one object it merges the properties of the objects into a new object. If the same properties exist in multiple spread objects, the one from the later object wins. Are you expecting it to append objects into a new parent structure? Or what did you expect to see?

If you want the objects placed into a parent object, try this:

const us = { me, you }

Or a parent array:

const we = [ me, you ]

Upvotes: 1

Andy
Andy

Reputation: 1386

The spread syntax in object literals copies object properties onto a new object.

From the MDN docs:

The Rest/Spread Properties for ECMAScript proposal (stage 4) adds spread properties to object literals. It copies own enumerable properties from a provided object onto a new object.

And the provided example is as follows:

var obj1 = { foo: 'bar', x: 42 };
var obj2 = { foo: 'baz', y: 13 };

var clonedObj = { ...obj1 };
// Object { foo: "bar", x: 42 }

var mergedObj = { ...obj1, ...obj2 };
// Object { foo: "baz", x: 42, y: 13 }

Upvotes: 0

atiq1589
atiq1589

Reputation: 2327

See the results. mergeMeAndYou function replace 'me' object by 'you' and mergeYouAndMe function replace 'you' object by me

let me={
    name:"Shivendra",
    age:21
}


let you={
    name:"Neha",
    age:22
}


let mergeMeAndYou={
    ...me, ...you
}

let mergeYouAndMe={
    ...you, ...me
}

console.log(mergeMeAndYou);

console.log(mergeYouAndMe);

Upvotes: 0

Related Questions