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

163
Vistas
objetos profundos generados dinámicamente

Quiero pedir ayuda con el problema. Tengo un objeto Javascript profundo existente desde el cual quiero generar dinámicamente múltiples versiones. Tengo un método que tiene 2 parámetros. primero: el objeto del que quiero generar nuevos, segundo: un número o una matriz de números

por ejemplo:

 let myObj = { brown: { 50: '#f9f8f2', 100: '#f3f0e6', }, singleProp: '#e6b01e', propLvl1: { color: '#32a852', sub1: { color: '#44eff2', sub2: { color: '#f2448d' }, }, }, };

myFunction(myObject, [10, 30]);

mi objetivo seria:

 MY-10-brown: { 50: '#(DYNAMICVALUE)f9f8f2', 100: '#(DYNAMICVALUE)f3f0e6', }, MY-10-singleProp: '#(DYNAMICVALUE)e6b01e', MY-10-propLvl1: { color: '#(DYNAMICVALUE)32a852', sub1: { color: '#(DYNAMICVALUE)44eff2', sub2: { color: '#(DYNAMICVALUE)f2448d' }, }, } MY-30-brown: { 50: '#(DYNAMICVALUE)f9f8f2', 100: '#(DYNAMICVALUE)f3f0e6', }, MY-30-singleProp: '#(DYNAMICVALUE)e6b01e', MY-30-propLvl1: { color: '#(DYNAMICVALUE)32a852', sub1: { color: '#(DYNAMICVALUE)44eff2', sub2: { color: '#(DYNAMICVALUE)f2448d' }, }, }

Hasta ahora lo he alcanzado:

 export default function generateObjects(obj, numbers) { let newObj = {}; for (let q = 0; q < transparentValue.length; q += 1) { let Obj = doTheJob(obj, transparentValue[q]); Object.assign(newObj, Obj); } return newObj; } function doTheJob(obj, number) { const newObj = {}; let newKey = ''; Object.keys(obj).forEach(function (key) { let trim = `${obj[key]}`.substring(1); let newValue = `#${anotherObject[number]}${trim}`; if (typeof obj[key] === 'object') { newKey = `MY-${number}-${key}`; newObj[newKey] = obj[key]; generateNewObj(newObj[newKey], number); return; } if (typeof obj[key] === 'string') { newObj[key] = newValue; } }); return newObj; }
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Podría crear nuevas propiedades para el primer nivel del objeto y tomar copias de los datos.

 const copy = value => typeof value === 'object' ? Object.fromEntries(Object.entries(value).map(([k, v]) => [k, copy(v)])) : typeof value === 'string' ? value.replace('#', '#DYNAMICVALUE') : value create = (object, values, header) => Object.fromEntries(Object .entries(object) .reduce((r, [k, v]) => [...r, ...values.map(i => [[header, i, k].join('-'), copy(v)])], []) ), myObj = { brown: { 50: '#f9f8f2', 100: '#f3f0e6' }, singleProp: '#e6b01e', propLvl1: { color: '#32a852', sub1: { color: '#44eff2', sub2: { color: '#f2448d' } } } }; console.log(create(myObj, [10, 30], 'my'));
 .as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Denunciar

0

Puedes:

  • Crear un nuevo objeto

  • Recorra cada número en la matriz

    • Dentro del bucle, recorra cada propiedad del objeto y asigne el valor de la propiedad a la propiedad modificada del nuevo objeto ( "MY-"+num+"-"+prop ).

 let myObj = { brown: { 50: '#f9f8f2', 100: '#f3f0e6', }, singleProp: '#e6b01e', propLvl1: { color: '#32a852', sub1: { color: '#44eff2', sub2: { color: '#f2448d' }, }, }, }; function process(obj, numArr){ const newObj = {}; for(const num of numArr){ for(const prop in obj){ newObj['MY-'+num+'-'+prop] = obj[prop]; } } return newObj; } console.log(JSON.stringify(process(myObj, [10, 30]), 0, 2))
 .as-console-wrapper{max-height:100%!important;top:0}

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