![](/img/trans.png)
[英]Turning an array of objects, into a single object with the same value for all keys?
[英]How can I convert an array of objects into single object while keys of all the objects are same and value may differ
我正在尝试转换:
var arr = [{ "name": "value1" }, { "name": "value2" }, { "name": "value3" }];
var obj = {}; //create the empty output object
arr.forEach(function (item, i) {
var key = Object.keys(item)[0];
obj[key] = item[key];
});
console.log("obj",obj);
这只会给我最后一个 object 作为{name: "value3"}
预期的结果将是:
{ name: "value1", name : "value2", name: "value3" }
根据上面的评论,您想要的 output object 不能有重复的属性,而是可以在数组中。
const arr = [{ "name": "value1" }, { "name": "value2" }, { "name": "value3" }];
const output = {};
// Iterate through each object in your array
arr.forEach(object => {
// For each entry in your object, in this case we only have name
for(let [key, value] of Object.entries(object)) {
// If the key's value isn't an array, we will assign a new one
if(!Array.isArray(output[key])) {
output[key] = [];
}
// Push the value to the output object key's array
output[key].push(value);
}
});
// Expected { name: ["value1", "value2", "value3"] }
console.log(output);
ES6 符号可以用作对象的相同属性名称。 然而,每个符号都是独一无二的。 现在,我能为您的问题找到的唯一解决方案是使用 Symbol 作为我们的密钥。 因为通常对象不能有两个相同的键。
看看下面的代码是否有帮助。
const arrQuestion = [{ "name": "value1" }, { "name": "value2" }, { "name": "value3"
}];
const ourObj = {};
arrQuestion.forEach(obj => {
let symbol = Symbol("name");
ourObj[symbol] = obj.name;
});
console.log(ourObj);
希望这可以帮助:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.