我正在寻找一种采用以下列表的方法:
directory = [
{
name: "Albert",
age: 40,
gender: "M"
},
{
name: "Suzanne",
age: 27,
gender: "F"
},
{
name: "Robert",
age: 19,
gender: "M"
},
{
name: "Connie",
age: 87,
gender: "F"
}
]
并在键
name
上制作字典:dictionary = {
"Albert": {
name: "Albert",
age: 40,
gender: "M"
},
"Suzanne": {
name: "Suzanne",
age: 27,
gender: "F"
},
"Robert": {
name: "Robert",
age: 19,
gender: "M"
},
"Connie": {
name: "Connie",
age: 87,
gender: "F"
}
}
这类似于C#
ToDictionary
方法。我知道我可以做类似在directory
循环或for
调用中遍历.each
的操作,并在每次迭代中修改dictionary
的值。但是,我宁愿进行类似函数式编程的赋值,例如dictionary = directory.toDictionary(p => p.name);
例如在ES6或lodash中是否存在这种方法?
最佳答案
您可以映射键和值,并使用(即将出现的)Object.fromEntries
从此数组创建对象。
var directory = [{ name: "Albert", age: 40, gender: "M" }, { name: "Suzanne", age: 27, gender: "F" }, { name: "Robert", age: 19, gender: "M" }, { name: "Connie", age: 87, gender: "F" }],
result = Object.fromEntries(directory.map(o => [o.name, o]));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
经典方法
var directory = [{ name: "Albert", age: 40, gender: "M" }, { name: "Suzanne", age: 27, gender: "F" }, { name: "Robert", age: 19, gender: "M" }, { name: "Connie", age: 87, gender: "F" }],
result = Object.assign({}, ...directory.map(o => ({ [o.name]: o })));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 等效于C#ToDictionary的JavaScript,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57083752/