0

I have data that looks like this.

[
  {
    key: 'myKey'
    value: 'myValue'
  },
  {
    key: 'mySecondKey'
    value: 'mySecondValue'
  },
  {
    key: 'myThirdKey'
    value: 'myThirdValue'
  },
]

The amount of objects varies depending on how much values an account has set. I'm trying to return this in a format that looks like this

{
  mykey: 'myValue'
  mySecondKey: 'mySecondValue'
  myThirdkey: 'myThirdValue'
}

Any advice on how I would go about doing this?

Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42
Croisade
  • 225
  • 2
  • 12

3 Answers3

2

You can do something, like

const src = [{key:'myKey',value:'myValue'},{key:'mySecondKey',value:'mySecondValue'},{key:'myThirdKey',value:'myThirdValue'},],

    result = Object.assign({}, ...src.map(o => ({[o.key]: o.value})))
    
console.log(result)
.as-console-wrapper{min-height:100%;}
Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42
1

You can use reduce for this:

const data = [{key:"myKey",value:"myValue"},{key:"mySecondKey",value:"mySecondValue"},{key:"myThirdKey",value:"myThirdValue"}];

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

console.log(res);
blex
  • 24,941
  • 5
  • 39
  • 72
0

Other answers work but I feel like they are a bit complicated, here's a simple for of loop:

const data = [
  {
    key: 'myKey',
    value: 'myValue'
  },
  {
    key: 'mySecondKey',
    value: 'mySecondValue'
  },
  {
    key: 'myThirdKey',
    value: 'myThirdValue'
  }
];

const result = {};

for(const {key, value} of data) {
  result[key] = value;
}

console.log(result);