skip to Main Content

How to separate the Array to objects,

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

Kindly help me in this. Thanks in Advance

3

Answers


  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
            }
        }
    ]
    
    Login or Signup to reply.
  2. we can do this via forEach though not an efficient way

    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);
    Login or Signup to reply.
  3. arr.reduce((acc, curr) => {
      acc[curr.name] = curr;
      return acc;
    }, {});
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search