Reputation: 3099
Please see code below. Is there a more succinct way to transform the originalObject
into myObject
?
The key is that I'm trying to set myObject
's property names based on the id
within each property in originalObject
.
myObject = Object
.values( originalObject )
.reduce( (acc, x) => {
let propHolder = {}
propHolder[x.id] = false
return Object.assign( acc, propHolder )
}, {} )
Upvotes: 0
Views: 101
Reputation: 665060
See Ryan’s answer for elegant but long one-liners. But since you were asking for a succinct way, here's the simple solution:
myObject = {};
for (const k in originalObject)
myObject[originalObject[k].id] = false;
Or possibly more interesting:
myObject = {};
for (const {id} of Object.values(originalObject))
myObject[id] = false;
Upvotes: 2
Reputation: 225095
Since you have let
, you have computed properties:
myObject = Object.values(originalObject).reduce((acc, x)=>{
return Object.assign(acc, {[x.id]: false})
},{})
Now since the arrow function is just a return:
myObject =
Object.values(originalObject)
.reduce((acc, x) => Object.assign(acc, {[x.id]: false}), {})
and if you don’t mind making an array:
myObject =
Object.values(originalObject)
.map(x => ({[x.id]: false}))
.reduce(Object.assign, {});
I would prefer to have a fromPairs
function on hand, though.
myObject = fromPairs(
Object.values(originalObject)
.map(x => [x.id, false])
);
If you use Lodash’s fromPairs
, you can also use its map
.
myObject = _.fromPairs(
_.map(originalObject, x => [x.id, false])
);
Upvotes: 2
Reputation: 1862
You can make use of Javascript's spread
syntax:
const myObject = Object
.values(originalObject)
.reduce((acc, x) => ({ ...acc, [x.id]: false }), {})
More reading: Spread syntax
Upvotes: 1