LovelyAndy
LovelyAndy

Reputation: 891

Turning an array of objects, into a single object with the same value for all keys?

I am working on a list of optional checkbox elements and want to have a checkAll function. With this function I am passing the rowsArray as the argument and want to turn it from an array of objects to one single object, with all the options in there with their ids as the key and their value as true.

So from this rowsArray
[{name: '0years', id: '0 TO 1'}, {name: '1years', id: '1 TO 2'}{name: '2years', id: '2 TO 3'}, ~~~~~] (there are 17 objects inside)

to this return{ '-1 TO 0': true, '0 TO 1': true,'1 TO 2': true }

I don't need the name value anymore and want to give it a new value of true, but am not sure how to add that.

So far I have this, but I am not sure where to go from here:

function convertRowsToObject(rowsArray) {
        // rowsArray [{name: '', id: '-1 TO 0'}, {name: '', id: '1 TO 2'}]
        // return an object that looks like
        // { '-1 TO 0': true, '1 TO 2': true }
       let allTrue = Object.assign({}, ...rowsArray)
        console.log(`rowsArray → `, rowsArray)
        return {}
      }

This unfortunately only gives me back the final object of the array 17 times...

allTrue → {name: '100+ years', id: "100 TO 150"}

Should I be using reduce here? Removing the name and replacing it with a single value of 'true' is stumping me.

Any ideas on how to progress with this?

Cheers!

Upvotes: 1

Views: 62

Answers (1)

Guerric P
Guerric P

Reputation: 31805

You could use Array.prototype.reduce() like this:

const rowsArray = [{name: '', id: '-1 TO 0'}, {name: '', id: '1 TO 2'}];

function convertRowsToObject(rowsArray) {
  // rowsArray [{name: '', id: '-1 TO 0'}, {name: '', id: '1 TO 2'}]
  // return an object that looks like
  // { '-1 TO 0': true, '1 TO 2': true }
  return rowsArray.reduce((acc, { id }) => ({ ...acc, [id]: true }), {});
}

const result = convertRowsToObject(rowsArray);

console.log(result);

Not sure why you need this though, because the true value doesn't provide any information, a simple array may be enough:

const rowsArray = [{name: '', id: '-1 TO 0'}, {name: '', id: '1 TO 2'}];

function convertRowsToObject(rowsArray) {
  return rowsArray.map(({ id }) => id);
}

const result = convertRowsToObject(rowsArray);

console.log(result);

Upvotes: 1

Related Questions