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

258
Vistas
Best way to alter array of objects inside an object (using a string path)

This may be simpler than I think but is there an easy way to alter the array inside this object using a string:

var temp = {
    members: [
    {file_name: 'abc', file_link: 'www'}
  ]
}

This is what I am trying to achieve:

const name = "members[0].file_name" // STRING
temp = {...temp, [name]: 'changed'}

Output it's giving me:

enter image description here

Yes I can split that string to give me the keys and index then change the object the normal way but I was just wondering if there is an easier way about it.

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

0

You can use the eval() function which will return the object you want in accordance with a path

const temp = {
  members: [{
    file_name: 'abc',
    file_link: 'www'
  }]
}

const path = "members[0].file_name";

// Obtain last key (file_name)
const lastKey = path.split(".").at(-1);
// Obtain the path to the last key (members[0])
const previousPath = path.substr(0, path.length - (lastKey.length + 1));
// Get the object with the path (temp.members[0])
const e = eval(`temp.${previousPath}`)
// Modify object
e[lastKey] = "xyz";

console.log(temp)

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can take a look at lodash's set function that takes in a string path, and returns the nested object.

lodash does the parsing for you, so you don't have to

https://dustinpfister.github.io/2018/12/04/lodash_set/

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can achieve this the following way

var temp = {
    members: [
    {file_name: 'abc', file_link: 'www'}
  ]
}

const name = "file_name" // STRING
temp.members[0][name] = "changed";

console.log(temp);

Or like this:

var temp = {
    members: [
    {file_name: 'abc', file_link: 'www'}
  ]
}

const name = "file_name";
const arr = "members";
temp[arr][0][name] = "changed";

console.log(temp);

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