Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

111
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda