Home > Back-end >  how do you turn this into this?
how do you turn this into this?

Time:10-08

I have an array:

const arr = [
   { name: "Jeff", id: 1 },
   { name: "Mary", id: 2 },
   { name: "Jeff", id: 3 },
   { name: "Mary", id: 4 },
   { name: "Emile", id: 5 },
];

I want to turn it into this:

const obj = {
    Jeff: [1, 3],
    Mary: [2, 4],
    Emile: [5],
};

I tried using the Array.reduce method, but I can't seem to wrap my head around the logic.

const obj = arr.reduce((acc, info) => {
    acc[info[name]] = .... 
    return acc;
}, {});

I assume it can be done with the reduce method

CodePudding user response:

You are on the right track, you just need to check to see if the array is there.

const arr = [
   { name: "Jeff", id: 1 },
   { name: "Mary", id: 2 },
   { name: "Jeff", id: 3 },
   { name: "Mary", id: 4 },
   { name: "Emile", id: 5 },
];

const result = arr.reduce((acc, { name, id }) => {
  acc[name] = acc[name] || [];  // or if(!acc[name]) acc[name] = [];
  acc[name].push(id);
  return acc;
}, {});

console.log(result);

CodePudding user response:

You can do like this:

const arr = [
  { name: "Jeff", id: 1 },
  { name: "Mary", id: 2 },
  { name: "Jeff", id: 3 },
  { name: "Mary", id: 4 },
  { name: "Emile", id: 5 },
];

const result = arr.reduce(
  (acc, cur) => ((acc[cur.name] || (acc[cur.name] = [])).push(cur.id), acc),
  {}
);

console.log(result);

  • Related