'javascript create dictionary from array
I have an array like this
propertiesToCheck: [
{name: 'name', type: 'type', enabled: true},
{
name: 'name2',
type: 'type2',
templateUrl: 'something.html',
preferences: {
places: [place1, place2,...],
placesDict: ????
},
enabled: true
}
]
In the places array there are objects with id, name, etc. Now I want to create a dictionary placesDict that should look like {place1.id: 0, place2.id: 0, ...}, so all values will be set to 0. How can I do that?
Solution 1:[1]
Better option in modern JS (>2019) is to use. It requires to have an Array of tuples (Array of Arrays). In following call I am extending Array with the map function which constructs the "nested array".
> const x = ["a", "b", "3"];
> Object.fromEntries(x.map(i => [i, undefined]));|
{ '3': undefined, a: undefined, b: undefined }
You can use the spread operator with following result:
> x = [1,2,3]
[ 1, 2, 3 ]
> {...x}
{ '0': 1, '1': 2, '2': 3 }
Solution 2:[2]
In Ramda for instance:
var createDict = R.pipe(R.pluck('id'), R.map(R.pair(R.__, 0)), R.fromPairs);
var places = [{ id: 'place1id' }, { id: 'place2id' }];
var placesDict = createDict(places);
// {"place1id": 0, "place2id": 0}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ond?ej KolĂn |
| Solution 2 | elpddev |
