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

142
Vistas
Unir una matriz de claves de objetos con el "mismo" nombre en una matriz

Estoy intentando unir una matriz de objetos con las "mismas" claves que una matriz. Básicamente, lo que quiero decir con "mismas teclas" es que estas teclas variarán solo en número, lo cual no importa. Por ejemplo:

 { names.0.id: "Here" } { names.1.id: "Almost" } { names.2.id: "There" } ...

Quiero unir todas las claves que tienen la siguiente sintaxis en una sola. Me gusta:

 { names: ["Here", "Almost", "There"] }

Tengo una matriz de matrices que contienen estos datos.

 [{ "id": "123" }, { "group_name": "Test Group" }, { "admin": "Somthing" }, { "email_address": "Somthing@here.com" }, { "org.id": "4" }, { "created_by": "6" }, { "updated_by": "6" }, { "students.0.id": "Yes" }, { "students.1.id": "No" }, { "names.0.id": "Here" }, { "names.1.id": "Almost" }, { "names.2.id": "There" }], [{ "id": "125" }... ] ...

Lo que me gustaría lograr:

 [{ "id": "123" }, { "group_name": "Test Group" }, { "admin": "Somthing" }, { "email_address": "Somthing@here.com" }, { "org.id": "4" }, { "created_by": "6" }, { "updated_by": "6" }, { "students": ["Yes", "No"] }, { "names": ["Here", "Almost", "There"] }]

Para cualquier otra clave que tenga esta sintaxis de:

 name.number.id

Siempre me gustaría unirme en una sola matriz con la primera parte del nombre

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

0

Sugeriría dividir el problema en tres partes:

  1. Transforme sus matrices de objetos { key: value } en objetos anidados únicos
  2. Aplane dichos objetos anidados para reemplazar los objetos { id: ... } solo con sus valores
  3. Traducir de nuevo a un objeto por par clave-valor

1. Fusionar a un solo objeto

Para construir un objeto anidado, dividimos cada clave por "." . Luego recorremos las claves en pares para crear nuestras capas anidadas. Cuando una clave es numérica, agregamos una matriz. Vea mergeKvp en el fragmento a continuación.

2. Aplanamiento para deshacerse de { id }

Para aplanar, atravesamos el árbol. Cada vez que vemos un objeto que solo tiene una propiedad de id , lo reemplazamos por el valor de identificación de ese objeto. Vea flattenObj en el fragmento a continuación.

 //// UTILS // Merge a key value pair in to an object splitting by "." const mergeKvp = (obj, [key, value]) => { const path = key.split("."); let target = obj; for (let i = 0; i < path.length - 1; i += 1) { const k1 = path[i]; const k2 = path[i + 1]; if (!target[k1]) target[k1] = isNaN(+k2) ? {} : []; target = target[k1]; } target[path.at(-1)] = value; return obj; } // Flatten a nested object structure const flattenObj = obj => { // Handle arrays if (Array.isArray(obj)) return obj.map(flattenObj); // Handle objects if (Object(obj) === obj) { // Replace { id: _ } objects with _ if ("id" in obj && Object.keys(obj).length === 1) return obj.id; // Recurse for other objects return Object.fromEntries( Object.entries(obj).map(([k, v]) => [k, flattenObj(v)]) ); } // Return value for everything else return obj; } //// APP // Merge KVP objects in to one big object const base = Object.assign({}, ...getData()); // Create nested structures out of the dot-keys const tree = Object.entries(base).reduce(mergeKvp, {}) // Flatten the tree const output = flattenObj(tree); // Translate back to array of { key: value } objects console.log( Object.entries(output).map(([k, v]) => ({ [k]: v })) ); function getData() { return [{ "id": "123" }, { "group_name": "Test Group" }, { "admin": "Somthing" }, { "email_address": "Somthing@here.com" }, { "org.id": "4" }, { "created_by": "6" }, { "updated_by": "6" }, { "students.0.id": "Yes" }, { "students.1.id": "No" }, { "names.0.id": "Here" }, { "names.1.id": "Almost" }, { "names.2.id": "There" }]; };

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