2

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.

1
  • you will have to go with lodash Commented Feb 26, 2022 at 15:07

3 Answers 3

1

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/

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I tried using the eval function without splitting the key but I could get it to work properly. Lodash works fine!
1

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)

2 Comments

Thanks Alex. Yes I did come across a similar answer in another thread but I was wondering if I can do that without splitting the string. I went with the lodash approach but this is a good solution too!
@SFaz Since there isn't a copy-by-reference operator in js, you will need to split last key in order to modify the actual object. Glad to help!
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.