如何将一个对象的元素推入另一个对象?

How to push elements of an object into another object?

与数组一样,我们可以使用数组.push(item) 添加新元素。如何对 objects 做同样的事情?它可以在对象内部完成吗?喜欢:

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

您可以像这样简单地添加对象的一些属性:

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

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

更新:

在那种情况下就这样做:

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

要过滤掉循环体内不需要的属性,您也可以这样做:

for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
        myObj[prop] = obj[prop];
    }
}

您可以使用jQuery.extend()函数

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

jQuery.extend(myObject, anothObject);
console.log(myObject);

您可以使用jQuery的扩展函数: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 );

非jquery选项:您可以迭代要合并的对象的键。

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

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

循环结束时anothObject{lemon: "l", apple: "a", orange: "o"}

要将一个对象的所有元素复制到另一个对象,请使用 Object.assign:

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

或者,更优雅的 ES6 风格使用 spread ... operator:

let myObject = { apple: "a", orange: "o" };
let anothObject = { lemon: "l", ...myObject };
var addToObject = function (obj, key, value, index) {

// Create a temp object and index variable
var temp = {};
var i = 0;

// Loop through the original object
for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) {

        // If the indexes match, add the new item
        if (i === index && key && value) {
            temp[key] = value;
        }

        // Add the current item in the loop to the temp obj
        temp[prop] = obj[prop];

        // Increase the count
        i++;

    }
}

// If no index, add to the end
if (!index && key && value) {
    temp[key] = value;
}

return temp;

};