Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

108
Views
Javascript Object Structure Without Key

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!

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report

0

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);

about 4 years ago · Juan Pablo Isaza Report

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!