Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

252
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda