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

196
Vistas
¿Cómo establecer claves de objetos en denominadores comunes?

Tengo una matriz de objetos y quiero que todos los objetos de la matriz tengan las mismas claves.

 var obj1 = {"type": "test", "info": "a lot", "value": 7}; var obj2 = {"value": 5}; var obj3 = {"context": "demo", "info": "very long", "value": 3}; var obj4 = {"info": "no way"}; var dataSet = [obj1,obj2,obj3,obj4];

Mi intento es crear una matriz con todas las claves posibles en el primer paso. Luego recorra esa matriz de claves y actualice los objetos si no se encontró la clave.

 keys.forEach(function(a,b){ dataSet.forEach(function(c,d){ //key not found if(a in c === false) { //add key to object dataSet[b][a] = false; } }); });

Sin embargo, no parece funcionar correctamente. Esta es mi salida:

 after logic: [ { "type": false, "info": "a lot", "value": 7 }, { "value": 5, "info": false }, { "context": "demo", "info": "very long", "value": false }, { "info": "no way", "context": false } ]

¿Qué me estoy perdiendo allí?

 var obj1 = {"type": "test", "info": "a lot", "value": 7}; var obj2 = {"value": 5}; var obj3 = {"context": "demo", "info": "very long", "value": 3}; var obj4 = {"info": "no way"}; var dataSet = [obj1,obj2,obj3,obj4]; var keys = []; console.log("before logic: ", dataSet); //Step 1: Fill keys array dataSet.forEach(function(a,b){ Object.keys(a).forEach(function(c,d) { //add keys to array if not already exists if(!keys.includes(c)) { keys.push(c); } }); }); //Step2: loop through keys array and add key to object if not existing keys.forEach(function(a,b){ dataSet.forEach(function(c,d){ //key not found if(a in c === false) { //add key to object dataSet[b][a] = false; } }); }); console.log("after logic: ", dataSet);

EDITAR:

Sería perfecto si las claves también estuvieran siempre ordenadas en el mismo orden.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Simplemente puede recopilar las claves en un Set usando flatMap() y luego asignar las que faltan usando forEach() :

 const dataSet = [ {"type": "test", "info": "a lot", "value": 7}, {"value": 5}, {"context": "demo", "info": "very long", "value": 3}, {"info": "no way"} ]; const keys = new Set(dataSet.flatMap(Object.keys)); dataSet.forEach((v) => keys.forEach((k) => v[k] = k in v ? v[k] : false)); console.log(dataSet);


Para abordar la solicitud adicional de tener las claves en el mismo orden, tenga en cuenta que, históricamente, las propiedades de los objetos de JavaScript no estaban ordenadas, por lo que confiar en el orden de las propiedades de los objetos en JavaScript casi nunca es una buena idea.

Dicho esto, es difícil obtener un orden fijo al modificar los objetos existentes, pero es factible si crea objetos nuevos:

 const dataSet = [ {"type": "test", "info": "a lot", "value": 7}, {"value": 5}, {"context": "demo", "info": "very long", "value": 3}, {"info": "no way"} ]; const keys = [...new Set(dataSet.flatMap(Object.keys))]; const result = dataSet.map((v) => keys.reduce((a, k) => ({ ...a, [k]: k in v ? v[k] : false }), {})); console.log(result);

about 4 years ago · Juan Pablo Isaza Denunciar

0

El problema con su código es básicamente un error tipográfico: está utilizando el índice incorrecto cuando configura la clave:

 dataSet[b][a] = false;

b es el índice de la clave en keys , no el índice del objeto en dataSet . No necesita hacer esa indexación en absoluto, solo haga:

 c[a] = false;

Es mucho más fácil seguir lo que está haciendo cuando usa nombres significativos para las variables en lugar de a , b , c y d . Aquí está su código con un cambio de nombre razonable y con el cambio descrito anteriormente:

 var obj1 = { type: "test", info: "a lot", value: 7 }; var obj2 = { value: 5 }; var obj3 = { context: "demo", info: "very long", value: 3 }; var obj4 = { info: "no way" }; var dataSet = [obj1, obj2, obj3, obj4]; var keys = []; console.log("before logic: ", JSON.stringify(dataSet, null, 4)); //Step 1: Fill keys array dataSet.forEach(function (obj) { Object.keys(obj).forEach(function (key) { //add keys to array if not already exists if (!keys.includes(key)) { keys.push(key); } }); }); //Step2: loop through keys array and add key to object if not existing keys.forEach(function (key) { dataSet.forEach(function (obj) { //key not found if (key in obj === false) { //add key to object obj[key] = false; } }); }); console.log("after logic: ", JSON.stringify(dataSet, null, 4));
 .as-console-wrapper { max-height: 100% !important; }

Pero ese código puede ser mucho más simple usando un Set y funciones de lenguaje modernas:

 const obj1 = { type: "test", info: "a lot", value: 7 }; const obj2 = { value: 5 }; const obj3 = { context: "demo", info: "very long", value: 3 }; const obj4 = { info: "no way" }; const dataSet = [obj1, obj2, obj3, obj4]; const keys = new Set(); // *** Use a set console.log("before logic: ", dataSet); // Step 1: Fill keys array for (const obj of dataSet) { for (const key of Object.keys(obj)) { keys.add(key); } } // Step2: loop through keys array and add key to object if not existing for (const key of keys) { for (const obj of dataSet) { if (!(key in obj)) { obj[key] = false; } } } console.log("after logic: ", JSON.stringify(dataSet, null, 4));
 .as-console-wrapper { max-height: 100% !important; }

Robby Cornelissen lo lleva mucho más allá , pero quería mostrarlo usando bucles simples.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Puede crear un objeto de 'plantilla' a partir del Set de claves combinadas y luego simplemente Object.assign un objeto a esta plantilla desde cada objeto. Esto le dará todas las propiedades en un orden consistente.

 const dataSet = [ { "type": "test", "info": "a lot", "value": 7 }, { "value": 5 }, { "context": "demo", "info": "very long", "value": 3 }, { "info": "no way" } ]; const template = Object.fromEntries([...new Set(dataSet.flatMap(o => Object.keys(o)))].map(k => [k, false])); const result = dataSet.map(o => Object.assign({ ...template }, o)); console.log(result)

Alternativamente, puede crear la plantilla simplemente fusionando todos los objetos en el conjunto de datos y sobrescribiendo un valor predeterminado.

 const dataSet = [ { "type": "test", "info": "a lot", "value": 7 }, { "value": 5 }, { "context": "demo", "info": "very long", "value": 3 }, { "info": "no way" } ]; const template = Object.assign({}, ...dataSet); for (const k of Object.keys(template)) { template[k] = false; } const result = dataSet.map(o => Object.assign({ ...template }, o)); 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