0

I have an array that keep changing with the user input.

for example:

user = ['a','b',['c','d'],'e',['f','g',['h','i'],'j']]

I also have a pointer to point where to make a change.

pointer = [1] change value at user[1]
pointer = [2,1] change value at user[2][1]
pointer = [4,2,2] change value at user[4][2][2]

Dimension is mostly not the same and can be more than 10. Now I'm making a string then eval. Can I write a function without using eval?

1
  • 2
    What does your function look like? Commented Sep 5, 2015 at 19:19

2 Answers 2

2

Use lodash's _.set!

_.set(user, [4,2,1], '!')

Or, if you don't want lodash, you can implement this one yourself.

function setDeep(obj, path, val) {
    if (path.length === 1)
        obj[path[0]] = val;
    else
        setDeep(obj[path.shift()], path, val)
}
// then use: setDeep(user, [4,2,1], 'something').

Note that this version will throw if the specified key doesn't exist. This is also not a good example of clarity and maintainability, so you'll need to improve it, but it's a good starting point - it does what you want.

If you neet to get instead of set - use lodash's _.get or implement it yourself, it would be very similar to my setDeep.

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

1 Comment

This really help. Both ways work for me! Thanks a lot !
0

I assume that the user's input is a string and not an array like in your example, because you mentioned eval, otherwise it's a completely different approach.

var user = "['a','b',[4,'d'],'e',['f','g',['h','i'],'j']]";
JSON.parse(user.replace(/'/g, "\""));

2 Comments

Thanks. It works for string. User is an array to store user input and I allow a nested input. Sorry that my question is not clear.
Please thank me by clicking the top arrow on the left to my answer.

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.