Search code examples
javascriptarraysreduce

js object property creation from keys


hi I am trying to create a object map from array of objects using reduce method but did n't find a way to add 2 properties as key . Let say I have array of objects like -

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

i am trying to create a map like

{
  sam_26:{
      name: "sam",
      age: 26,
    }
 }

my code for reduce function :

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

this didn't work . any pointers will be helpful ..thanks!


Solution

  • Create the key with the values taken from the student object. Assign the current student to the obj (the accumulator) using the key:

    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);

    A generic approach that uses a callback to create the 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);