Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to push elements of an object into another object?

Like in arrays we can add new elements by using array.push(item). How to do the same with objects? And can it be done inside the object? Like:

var myObject={apple: "a", orange: "o"};
var anothObject = {lemon: "l", myObject};
like image 724
Rana Mallah Avatar asked Apr 29 '15 16:04

Rana Mallah


4 Answers

To copy all elements of one object to another object, use Object.assign:

var myObject = { apple: "a", orange: "o" };
var anothObject = Object.assign( { lemon: "l" }, myObject );

Or, more elegantly ES6 style using spread ... operator:

let myObject = { apple: "a", orange: "o" };
let anothObject = { lemon: "l", ...myObject };
like image 185
xor Avatar answered Oct 17 '22 21:10

xor


You could add some properties of an object simply like this :

obj = {a : "1", b : "2"};

myObj = {c: "3", d : "4"};
myObj.a = obj.a;
myObj.b = obj.b;

Update:

In that case just do this :

for(var prop in obj) myObj[prop] = obj[prop];

And to filter out the unwanted properties inside the loop body you could also do this :

for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
        myObj[prop] = obj[prop];
    }
}
like image 7
vjdhama Avatar answered Oct 17 '22 22:10

vjdhama


You can use jQuery's extend function: http://api.jquery.com/jquery.extend/

var object1 = {
  apple: 0,
  banana: { weight: 52, price: 100 },
  cherry: 97
};
var object2 = {
  banana: { price: 200 },
  durian: 100
};

// Merge object2 into object1
$.extend( object1, object2 );
like image 3
Jonathan.Brink Avatar answered Oct 17 '22 22:10

Jonathan.Brink


A non-jquery option: you could iterate of the keys of the object to be merged.

var myObject={apple: "a", orange: "o"};
var anothObject = {lemon: "l"};

Object.keys(myObject).forEach(function(key) {
    anothObject[key] = myObject[key];
});

At the end of the loop anothObject is {lemon: "l", apple: "a", orange: "o"}

like image 1
Olivia O. Avatar answered Oct 17 '22 22:10

Olivia O.