Home > OS >  Best way to alter array of objects inside an object (using a string path)
Best way to alter array of objects inside an object (using a string path)

Time:02-27

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.

CodePudding user response:

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/

CodePudding user response:

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)

CodePudding user response:

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);

  • Related