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

194
Views
Modificar un valor específico en un objeto anidado (JavaScript)

Tengo este tipo de objeto:

 const obj = { group: { data: { data: [ { id: null, value: 'someValue', data: 'someData' } ] } } };

Necesito editar este objeto para que siempre que null esté en el valor de la propiedad, se reemplace con alguna cadena.

Lo que significa que si la cadena de reemplazo será 'someId', el resultado esperado es:

 const obj = { group: { data: { data: [ { id: 'someId', value: 'someValue', data: 'someData' } ] } } };

Lo más cercano que encontré fue esto y esto , pero no logré manipular las soluciones allí para lo que necesito.

¿Cómo debería hacerlo?

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

0

Probablemente tenga problemas con los valores de la matriz. Pase el índice de la matriz para modificar. En este caso [0]

 obj.group.data.data[0].id = "someId"

EDITAR Esto actualizará todos los valores null de id dentro de la matriz data :

 obj.group.data.data.forEach(o => { if (o.id === null) { o.id = "someId" } })

Otra EDICIÓN

Aquí hay un algoritmo para verificar recursivamente todos los valores profundamente anidados en un objeto. Compilará una matriz de rutas de objetos donde viven los valores nulos. Hay un método auxiliar incluido para encontrar y actualizar el valor del objeto en la ruta dada en la matriz. Hay una demostración del programa en la consola.

 const object = { group: { data: { data: [ { id: null, value: "foo", data: [null, "bar", [null, { stuff: null }]] }, { id: null, value: null, data: { bar: [null] } }, { id: null, value: "foo", data: null }, { id: 4, value: "foo", data: "bar" }, { id: 4, value: "stuff", data: null } ] }, attributes: null, errors: ["stuff", null] } } const inspectProperty = (key, obj, path = "") => { if (typeof obj[key] === "object") { if (obj[key] instanceof Array) { return analyzeArray(obj[key], `${path ? path + "." : ""}${key}`); } return analyzeObj(obj[key], `${path ? path + "." : ""}${key}`); } return []; }; const analyzeKey = (obj, key, path = "") => { if (obj[key] === null) return [`${path ? path + "." : ""}${key}`]; return inspectProperty(key, obj, path).reduce((a, k) => [...a, ...k], []); }; const analyzeObj = (obj, path = "") => { return Object.keys(obj).map((item) => analyzeKey(obj, item, path)); }; const analyzeArray = (array, path) => { return array.map((item, i) => analyzeKey(array, i, path)); }; const updateNullValue = (path, value) => { let p = path.split("."); p.reduce((accum, iter, i) => { if (i === p.length - 1) { accum[iter] = value; return object; } return accum[iter]; }, object); }; let nullValues = analyzeObj(object)[0] console.log(nullValues) nullValues.forEach((nullVal, i) => { updateNullValue(nullVal, "hello-" + i) }) console.log(object)

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!