Issue
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
var placesDict = {};
propertiesToCheck[1].preferences.places.forEach(place => {
placesDict[place.id] = 0;
});
Same thing but using function definition instead of arrow function.
var placesDict = {};
propertiesToCheck[1].preferences.places.forEach(setPlace);
function setPlace (place) {
placesDict[place.id] = 0;
}
To have this functionality attached to a method of the preferences
object:
propertiesToCheck: [
{name: 'name', type: 'type', enabled: true},
{
name: 'name2',
type: 'type2',
templateUrl: 'something.html',
preferences: {
places: [place1, place2,...],
placesDict: () => {
newDict = {};
propertiesToCheck[1].preferences.places.forEach(place => newDict[place.id] = 0);
return newDict;
}
},
enabled: true
}
]
console.log(propertiesToCheck[1].preferences.placesDict()); // {place1.id: 0, place2.id: 0, ...}
Setting the property placesDict
to be equal to a function return value:
propertiesToCheck: [
{name: 'name', type: 'type', enabled: true},
{
name: 'name2',
type: 'type2',
templateUrl: 'something.html',
preferences: {
places: [place1, place2,...],
placesDict: createDict()
},
enabled: true
}
]
function createDict() {
var placesDict = {};
propertiesToCheck[1].preferences.places.forEach(place => {
placesDict[place.id] = 0;
});
}
I hope this helped.
Answered By - jakeehoffmann
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.