在Javascript中将数组分成多个对象

问题描述 投票:0回答:4

如何将数组分离为对象,

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 }]

请帮助我。预先感谢

javascript reactjs arrays javascript-objects
4个回答
1
投票

我们可以通过

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
投票
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
        }
    }
]

0
投票
arr.reduce((acc, curr) => {
  acc[curr.name] = curr;
  return acc;
}, {});

0
投票

您可以使用

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);
© www.soinside.com 2019 - 2024. All rights reserved.