javascript - lodash - Add object to another object - Stack Overflow

admin2025-04-22  0

I have user object

{first: "john", last: "doe"} 

How can I attach details object

{car: 'corolla', color: 'silver'}

So that the output would be

  {first: "john", last: "doe", details:  {car: 'corolla', color: 'silver'} }

I have tried _.merge, _.assign and both flat details object and I end up with

  {first: "john", last: "doe", car: 'corolla', color: 'silver'}

I have user object

{first: "john", last: "doe"} 

How can I attach details object

{car: 'corolla', color: 'silver'}

So that the output would be

  {first: "john", last: "doe", details:  {car: 'corolla', color: 'silver'} }

I have tried _.merge, _.assign and both flat details object and I end up with

  {first: "john", last: "doe", car: 'corolla', color: 'silver'}
Share Improve this question asked Aug 1, 2017 at 9:39 DeanoDeano 12.2k20 gold badges75 silver badges125 bronze badges 2
  • 3 Why use a framework when you can assign it directly? user.details = details? – evolutionxbox Commented Aug 1, 2017 at 9:41
  • make your code simple. Or its for training purposes? var user = {first: "john", last: "doe"}; user.details = {car: 'corolla', color: 'silver'} – Maxim Shoustin Commented Aug 1, 2017 at 9:41
Add a ment  | 

3 Answers 3

Reset to default 4

With plain Javascript, you could use Object.assign.

var object = { first: "john", last: "doe" } ,
    details = { car: 'corolla', color: 'silver' };
    
Object.assign(object, { details });

console.log(object);

Just assign the details object to details property of user:

var user = {first: "john", last: "doe"};
var details = {car: 'corolla', color: 'silver'};
user.details = details;
console.log(user);

In context of lodash , you can use _.assign(user,{details});

var user = {first: "john", last: "doe"};
var details = {car: 'corolla', color: 'silver'};

console.log(_.assign(user,{details}));
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745297099a295038.html

最新回复(0)