0

Say I have a string:

const test = "data[0][something][0][arrayOfStrings][0]";

and an object:

const object = {
    data: [
        {
            something: [
                {
                    arrayOfStrings: ['some string']
                }
            ]  
        }
    ]
}

And I want to use the string to set/add a new value to arrayOfStrings. How would I access the object at the location of arrayOfStrings using the given test string?

Bdh2991
  • 3
  • 1
  • 1
    Does this answer your question? [Accessing nested JavaScript objects and arrays by string path](https://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-and-arrays-by-string-path) – ASDFGerte Feb 17 '21 at 16:02
  • Note that the link is for reading, not writing. However, the general sentiment, and top solutions, can all be easily utilized for writing as well (e.g. lodash has a `.set` instead of `.get`, and changing the top solution to write instead of read is also not substantially difficult). – ASDFGerte Feb 17 '21 at 16:07
  • @ASDFGerte - then why not vote to close based upon that dupe? Did you downvote the answer for this reason too - but still not vote to close on the dupe? Please consider picking one or the other if you did downvote. The dupe has no feature for **updating** the value. Just like my deleted comment didn't. Thanks for your consideration. – Randy Casburn Feb 17 '21 at 16:24
  • [This answer from the dupe](https://stackoverflow.com/a/40785342/) is very relevant. Lodash already allows for quite a rich syntax for `_.set` and its alternative `_.get`. – VLAZ Feb 17 '21 at 16:31
  • @RandyCasburn I flagged it long before the answer, and lack 15 reputation to vote. If there is an existing dupe target, i rate new answers (after the link was added, plus margin to write the answer) more strictly. In this case, the added answer was inferior to an already existing answer before edits, and on a security related topic: omitting warnings about the use of `eval`. Yes, `eval` can be acceptable here, but it should always be handled with care. It felt like a short answer (even not precisely answering the topic), less informative than existing ones. – ASDFGerte Feb 17 '21 at 16:37
  • @ASDFGerte - thanks for taking the time to explain. Because of comments here, the answer has been improved remarkably. IMO, advocating the use of a library is not necessary a good idea. Why lodash over underscore over jQuery over xyz parser becomes the discussion. – Randy Casburn Feb 17 '21 at 16:42

1 Answers1

1

Explanation : The test string holds the location of the arrayOfStrings and holds both indices for array, and keys for objects. So, I modified the test string, and added quotes, so that, the eval() does not cause any problem.

Use of eval() : eval() is used to execute JavaScript code present in the form of string. Using it, you can both access, as well as modify the values.

You can read more about eval() here : eval() function

const object = {
  data: [{
    something: [{
      arrayOfStrings: ['some string']
    }]
  }]
}

const test = "data[0][something][0][arrayOfStrings][0]";

var testStr = test.replaceAll("[", "['").replaceAll("]", "']");

//accessing value
console.log(eval("object." + testStr));

//modifying value
var str = "new string";
eval("object." + testStr + `='${str}'`)
console.log(eval("object." + testStr));
Pranav Rustagi
  • 2,604
  • 1
  • 5
  • 18
  • @RandyCasburn downvotes can be for answers that are valid but not useful. 1. Before the edit that happened while I was writing this comment, this wasn't actually *setting* the value, just *getting* it. 2. I suspect the downvote might be for the usage of `eval` which I'd agree shouldn't be encouraged. – VLAZ Feb 17 '21 at 16:24
  • 1
    @VLAZ - Thanks for the clarity. I agree with "before the edit". I don't agree with "eval is evil" - I do believe Pranav could increase the quality of the answer by explaining the circumstances under which it is safe to use eval. I also believe the downvote should be removed "after the edit" because that is what the site is all about - downvotes to encourage edits that increate the quality of the answer. Or do I have that wrong? – Randy Casburn Feb 17 '21 at 16:29
  • @VLAZ Sorry! I was still modifying the answer. I didn't read the setting part earlier. And I agree that using `eval` is a bad approach, as JavaScript code shouldn't be in text form. But here, path is given in the form of string. So I guess, `eval()` can be used. – Pranav Rustagi Feb 17 '21 at 16:30
  • @RandyCasburn people are free to downvote for any reason they wish. It's their prerogative when they feel a post is no longer "bad". – VLAZ Feb 17 '21 at 16:31