Home > OS >  JavaScript: Transform array of objects to an object
JavaScript: Transform array of objects to an object

Time:09-21

I am making an app that uses sequelize and the JSON value returned is:

[
  { key: 'PREFIX', value: 'm.' },
  { key: 'OWNER_ID', value: '14901414891498' },
  { key: 'GUILD_ID', value: '525219058950109' }
]

But I want to know if is possible to reorganize this json object to something like this:

{ prefix: 'm.', owner_id: '330406276972412928', guild_id: '525219058950109'}

I searched some methods of JSON object manipulation with Javascript but none of them fit in my need.

CodePudding user response:

Using Array#reduce:

const data = [ { key: 'PREFIX', value: 'm.' }, { key: 'OWNER_ID', value: '14901414891498' }, { key: 'GUILD_ID', value: '525219058950109' } ];

const obj = data.reduce((acc, {key, value}) => ({
  ...acc, [key.toLowerCase()]: value
}), {});

console.log(obj);

CodePudding user response:

You can use Object.fromEntries and transform the objects into [key, value] tuples.

const data = [
  { key: 'PREFIX', value: 'm.' },
  { key: 'OWNER_ID', value: '14901414891498' },
  { key: 'GUILD_ID', value: '525219058950109' }
]

const newData = Object.fromEntries(data.map(({ key, value }) => 
  [key.toLowerCase(), value]))

console.log(newData)

  • Related