How to push elements of an object into another object?

浪子不回头ぞ 提交于 2019-12-05 04:55:16

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 );

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];
    }
}

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:

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

Note however, that while I write this, this is still in proposal stage, although support is quite widespread (it works in my browser).

var myObject={apple: "a", orange: "o"};
myObject.lemon = 1; // myObject is now {apple: "a", orange: "o", lemon: 1}
Olivia O.

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"}

You can use jQuery.extend() function

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

jQuery.extend(myObject, anothObject);
console.log(myObject);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!