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

246
Views
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 answers
Answer question

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 Report

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 Report

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 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!