我正在寻找一种采用以下列表的方法:

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/

10-11 14:21