gpt4 book ai didi

javascript - 从键创建js对象属性

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:20:50 32 4
gpt4 key购买 nike

您好,我正在尝试使用 reduce 方法从对象数组创建对象映射,但没有找到将 2 个属性添加为键的方法。假设我有一系列对象,例如 -

 const students = [
{
name: "sam",
age: 26,
},
{
name: 'john",
age: 30,
}
]

我正在尝试创建一个像

这样的 map
{
sam_26:{
name: "sam",
age: 26,
}
}

我的 reduce 函数代码:

students.reduce((obj, student) => {
`${obj[student.name]}_${obj[student.age]}` = student;
return obj;
}, {});

这没有用。任何指示都会有所帮助..谢谢!

最佳答案

使用从 student 对象中获取的值创建键。使用 key 将当前 student 分配给 obj(累加器):

const students = [{
name: "sam",
age: 26,
},
{
name: "john",
age: 30,
}
];

const result = students.reduce((obj, student) => {
const key = `${student.name}_${student.age}`;
obj[key] = student;
return obj;
}, {});

console.log(result);

使用回调创建 key 的通用方法:

const keyBy = (arr, cb) => 
arr.reduce((r, o) => {
const key = cb(o);
r[key] = o;
return r;
}, {});

const students = [{"name":"sam","age":26},{"name":"john","age":30}];

const result = keyBy(students, (o) => `${o.name}_${o.age}`);

console.log(result);

关于javascript - 从键创建js对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49973435/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com