提问人:Hari 提问时间:11/3/2023 更新时间:11/4/2023 访问量:65
在 Javascript 中将数组分成多个对象
Separate Array into multiple objects in Javascript
问:
如何将 Array 分离到对象,
Need to convert the following
arr = [
{ name: 'abc', age: 15, roll_no: 25 },
{ name: 'def', age: 10, roll_no: 20 },
{ name: 'xyz', age: 16, roll_no: 18 },
];
Expected Output :
arr = [ abc : { name: 'abc', age: 15, roll_no: 25 },
def : { name: 'def', age: 10, roll_no: 20 },
xyz : { name: 'xyz', age: 16, roll_no: 18 }]
请帮我解决这个问题。提前致谢
答:
-1赞
Avalon Lu
11/3/2023
#1
arr.map(a=>{return {[a.name]:a}})
//output
[
{
"abc": {
"name": "abc",
"age": 15,
"roll_no": 25
}
},
{
"def": {
"name": "def",
"age": 10,
"roll_no": 20
}
},
{
"xyz": {
"name": "xyz",
"age": 16,
"roll_no": 18
}
}
]
1赞
Afzal K.
11/3/2023
#2
我们可以通过一种不有效的方式做到这一点forEach
arr = [
{ name: 'abc', age: 15, roll_no: 25 },
{ name: 'def', age: 10, roll_no: 20 },
{ name: 'xyz', age: 16, roll_no: 18 },
];
// empty object
const obj = {};
// Looping through & adding
arr.forEach(item => {
obj[item.name] = item;
});
console.log(obj);
0赞
ONMNZ
11/3/2023
#3
arr.reduce((acc, curr) => {
acc[curr.name] = curr;
return acc;
}, {});
1赞
Yash Borda
11/4/2023
#4
可以使用该方法将数组转换为对象,其中键作为属性,值作为对象本身。reduce
name
const arr = [
{ name: 'abc', age: 15, roll_no: 25 },
{ name: 'def', age: 10, roll_no: 20 },
{ name: 'xyz', age: 16, roll_no: 18 },
];
const obj = arr.reduce((acc, item) => ({ ...acc, [item.name]: item }), {});
console.log(obj);
评论