Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add value in Object Angular 2 Typescript

Tags:

javascript

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?

like image 855
Fernando Herique Rubim Pioli Avatar asked Feb 09 '17 16:02

Fernando Herique Rubim Pioli


2 Answers

You can use Object.assign function

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

merged = Object.assign(obj, obj2);

working jsfiddle

like image 96
FabioG Avatar answered Sep 19 '22 23:09

FabioG


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);
like image 22
kind user Avatar answered Sep 22 '22 23:09

kind user