7

I'm working with Angular 2 ( typescript)

I have an Object:

obj = {
"cadSocios" : true
};

And I need to add to it other values:

obj2 = {
"name" : ['name1', 'name2'],
part : ['part1', 'part2']
};

My Final Object must be:

objFinal = {
"cadSocios" : true,
"name" : ['name1', 'name2'],
part : ['part1', 'part2']
};

How can I do this? in array can use .push, and Object?

0

2 Answers 2

8

You can use Object.assign function

obj = {
 "cadSocios" : true
};
obj2 = {
 "name" : ['name1', 'name2'],
 part : ['part1', 'part2']
};

merged = Object.assign(obj, obj2);

working jsfiddle

Sign up to request clarification or add additional context in comments.

Comments

6

Method 1.

Object.assign function, provided by ES6.

var obj1 = {
"cadSocios" : true
};

var obj2 = {
"name" : ['name1', 'name2'],
part : ['part1', 'part2']
};

var obj = Object.assign(obj1, obj2);

console.log(obj);

Method 2.

Simple for in loop.

var obj1 = {
  "cadSocios": true
};

var obj2 = {
  "name": ['name1', 'name2'],
  part: ['part1', 'part2']
};

for (prop in obj2) {
  if (obj2.hasOwnProperty(prop)) {
    obj1[prop] = obj2[prop];
  }
}

console.log(obj1);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.