var a = {};
a['fruit'] = "apple";
var b = {};
b['vegetable'] = "carrot";
var food = {};
输出变量'food'必须包含两个键值对。
答案 0 :(得分:31)
您可以使用Object.assign
。
var a = { fruit: "apple" },
b = { vegetable: "carrot" },
food = Object.assign({}, a, b);
console.log(food);

对于不支持Object.assign
的浏览器,您可以迭代属性并手动分配值。
var a = { fruit: "apple" },
b = { vegetable: "carrot" },
food = [a, b].reduce(function (r, o) {
Object.keys(o).forEach(function (k) { r[k] = o[k]; });
return r;
}, {});
console.log(food);

答案 1 :(得分:11)
实现方式:
1。使用JavaScript Object.assign()方法。
var a = {};
a['fruit'] = "apple";
var b = {};
b['vegetable'] = "carrot";
var food = Object.assign({}, a, b);
console.log(food);
2. 使用自定义功能。
var a = {};
a['fruit'] = "apple";
var b = {};
b['vegetable'] = "carrot";
function createObj(obj1, obj2){
var food = {};
for (var i in obj1) {
food[i] = obj1[i];
}
for (var j in obj2) {
food[j] = obj2[j];
}
return food;
};
var res = createObj(a, b);
console.log(res);
3。使用ES6 Spread operator。
let a = {};
a['fruit'] = "apple";
let b = {};
b['vegetable'] = "carrot";
let food = {...a,...b}
console.log(food)
答案 2 :(得分:3)
您可以在es6中使用spread运算符,但是您需要使用babel来将代码转换为跨浏览器友好。
const a = {};
a['fruit'] = "apple";
const b = {};
b['vegetable'] = "carrot";
const food = { ...a, ...b }
console.log(food)

答案 3 :(得分:1)
创建实用程序功能,它可以扩展对象,例如:
function extendObj(obj1, obj2){
for (var key in obj2){
if(obj2.hasOwnProperty(key)){
obj1[key] = obj2[key];
}
}
return obj1;
}
然后使用另一个对象扩展此food
对象。这是一个例子:
food = extendObj(food, a);
food = extendObj(food, b);