I am trying to generate an object structure like so:
{nums: {500: 0, 600: 0}}
I have a function that loops and returns numbers as shown in object: 500 & 600. However,
No matter what I try to create an object structure like the above, it does not work.
This is what I have an array of object as follows :
const scores = [ {score: 500}, {variant_id: 600} ]
How can I loop through the scores array of object and get a structure like: Number 0 in this example as a value that will be applicable to all scores.
{nums: {500: 0, 600: 0}}
What I have done is:
let filteredScores = [];
for (let i = 0; i < scores.length; i++) {
const element = scores[i];
filteredScores.push(element);
}
However, this does not lead to the desired results.
Any insights or input is much appreciated!
Couple of ideas using reduce() and Object.values().
const scores = [ {score: 500}, {variant_id: 600} ];
const result1 = scores.reduce((o, item) => {
o.nums[Object.values(item)[0]] = 0
return o;
}, { nums: {} });
console.log(result1);
// Basically the same thing, just more compact
const result2 = { nums: scores.reduce((o, item) => ({...o, [Object.values(item)[0]]: 0}), {})};
console.log(result2);
You can use Object.fromEntries in conjunction with Array#map. (To get the first property value of an object, you can retrieve the first element of the array returned by Object.values.)
const scores = [ {score: 500}, {variant_id: 600} ];
const res = {nums: Object.fromEntries(scores.map(x => [Object.values(x)[0], 0]))};
console.log(res);
var scores = [ {score: 500}, {variant_id: 600} ],
result = scores.reduce( (r,o) => ( Object.keys(o).forEach(k => r.nums[o[k]] = 0)
, r
)
, {nums:{}}
);
console.log(result);