如何在 Javascript 中合并两个字典?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43449788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I merge two dictionaries in Javascript?
提问by Ankur Gupta
var a = {};
a['fruit'] = "apple";
var b = {};
b['vegetable'] = "carrot";
var food = {};
The output variable 'food' must include both key-value pairs.
输出变量 'food' 必须包含两个键值对。
回答by Nina Scholz
You could use Object.assign.
你可以使用Object.assign.
var a = { fruit: "apple" },
b = { vegetable: "carrot" },
food = Object.assign({}, a, b);
console.log(food);
For browser without supporting Object.assign, you could iterate the properties and assign the values manually.
对于不支持 的浏览器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);
回答by Rohit Jindal
Ways to achieve :
实现方式:
1.Using JavaScript Object.assign()method.
1.使用 JavaScript Object.assign()方法。
var a = {};
a['fruit'] = "apple";
var b = {};
b['vegetable'] = "carrot";
var food = Object.assign({}, a, b);
console.log(food);
2.Using custom function.
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.Using ES6 Spread operator.
3.使用 ES6扩展运算符。
let a = {};
a['fruit'] = "apple";
let b = {};
b['vegetable'] = "carrot";
let food = {...a,...b}
console.log(food)
回答by synthet1c
You could use the spread operator in es6, but you would need to use babel to transpile the code to be cross browser friendly.
您可以在 es6 中使用扩展运算符,但您需要使用 babel 将代码转译为跨浏览器友好。
const a = {};
a['fruit'] = "apple";
const b = {};
b['vegetable'] = "carrot";
const food = { ...a, ...b }
console.log(food)
回答by Ashish Kumar
Create a Utility functionwhich can extend Objects, like:
创建一个可以扩展对象的实用函数,例如:
function extendObj(obj1, obj2){
for (var key in obj2){
if(obj2.hasOwnProperty(key)){
obj1[key] = obj2[key];
}
}
return obj1;
}
And then extend this foodobject with the another Objects. Here is example:
然后food用另一个对象扩展这个对象。这是示例:
food = extendObj(food, a);
food = extendObj(food, b);

