Home > Software design >  how to convert array to object of same key
how to convert array to object of same key

Time:01-12

I have a very simple thing I need to do, which is take an array/list of strings ['a.png', 'b.png', ...] and map it to an object with the same key "path" which looks like {path: 'a.png', path: 'b.png', ...}. How do I do this?

I've tried Object.assign to change the array to an object, which works, but then I can't figure out how to change all the keys to the same value. It is a long array so I don't want to do this manually. How do I assign all the keys in the object to "path"?

CodePudding user response:

You cannot have repeated keys in one object, instead you can create an array of objects to store all the paths there

const arr = ['a.png', 'b.png', 'c.png'];

const arrObj = arr.reduce((acc, prev) => {
  return [
    ...acc,
    {
      path: prev
    }
  ]
}, []);

console.log(arrObj);

CodePudding user response:

you can use a reduce, in this way, I hope this solution will be of great help to you

const object = array.reduce((acc, item) => { acc[path] = item return acc }, {})

  • Related