David V
David V

Reputation: 9

Converting array of object to en object with key : value dynamic

I have an array of objects which look like this:

stuff = [
    { value: 'elevator', checked: true },
    { value: 'something', checked: false },
    { value: 'else', checked: true },
]

And I am trying to get something like this:

{
    'elevator': true,
    'something: false,
    'else': true,
}

All I can get since yesterday is an array of objects like:

[
    { 'elevator': true },
    { 'something': false },
    { 'else': true }
];

I tried with mapping on array and then using Object.assign but it's not working. I get the previous code.

Upvotes: 0

Views: 35

Answers (4)

swaroop pallapothu
swaroop pallapothu

Reputation: 608

Iterate stuff array, So you will get each object under stuff. Then get that value that you need.

var stuff = [
   { value: 'elevator', checked: true },
   { value: 'something', checked: false },
   { value: 'else', checked: true },
];

var obj = {};
for( var i=0; i<stuff.length; i++) {
  obj[stuff[i]['value']] = stuff[i]['checked'];
}
console.log(obj);

Upvotes: 1

Faly
Faly

Reputation: 13356

If you can use ES6, you can do it with Object.assign, array.prototype.map, some destructuring, object litteral dynamic key and spread operator:

var stuff = [
    { value: 'elevator', checked: true },
    { value: 'something', checked: false },
    { value: 'else', checked: true },
];
var result = Object.assign({}, ...stuff.map(({value, checked}) => ({[value]: checked})));
console.log(result);

Upvotes: 0

Suren Srapyan
Suren Srapyan

Reputation: 68665

You can reduce function to make an single object from the given array. Just add your logic inside it. In this case, value to the property name and checked to it's value.

const stuff = [
    { value: 'elevator', checked: true },
    { value: 'something', checked: false },
    { value: 'else', checked: true },
]

const mapped = stuff.reduce((obj, item) =>  (obj[item.value] = item.checked, obj), {});

console.log(mapped);

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68393

Use reduce

var output  = stuff.reduce( (a,c) => (a[c.value] = c.checked, a) , {} )

Demo

var stuff = [
    { value: 'elevator', checked: true },
    { value: 'something', checked: false },
    { value: 'else', checked: true },
];
var output  = stuff.reduce( (a,c) => (a[c.value] = c.checked, a) , {} )
console.log( output );

Edit

Using object.assign

stuff.reduce( (a,c) => Object.assign( {}, a, { [c.value] : c.checked })  , {} )

Upvotes: 1

Related Questions