0

Current string: folder1/folder2/folder3

I need to convert in: ['folder1']['folder2']['folder3']

What I tried:

let folder = "folder1/folder2/folder3";

let splittedFolder = folder.split('/');
let newFolder = splittedFolder.join('[' ']');

I think I am absolutely wrong.... I want to achieve somethink like userDB['folder1']['folder2']['folder3'] to navigate into an Object and edit it.

2
  • Are you trying to create an array? Or a string containing []? Commented Feb 23, 2019 at 19:11
  • A string containing [] to go deeper in object :-) Commented Feb 23, 2019 at 19:11

1 Answer 1

1

You might split by slashes, then map to enclose each string with ['']s, then join again:

let folder = "folder1/folder2/folder3";
const output = folder
  .split('/')
  .map(str => `['${str}']`)
  .join('');
console.log(output);

But you can't navigate a normal object with a string like this unless you use eval, which you really shouldn't use. If the literal code

userDB['folder1']['folder2']['folder3']

would result in accessing the desired nested value, then to get to it from your input, use reduce instead:

const val = folder.split('/')
  .reduce((a, key) => a[key], userDB);

Or, to handle possible undefined objects in between:

const val = folder.split('/')
  .reduce((a, key) => a !== undefined ? a[key] : undefined, userDB);
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, it works! :) But how do I can remove the first? because will be an empty one: ['']
Do you mean that your real input string has a leading slash? If so, slice it off first. folder.slice(1).split(...
Thanks so much :) Your example from above works well. I get the value from the object. But what if I want to change this value? val = newValue; not works because the variable val "is never used", also if I change to let val...
Pop off the last substring from the array first, then use the same reduce method as above to get lastObj (while iterating over all but the last item in the array), then do lastObj[lastProp] = newVal

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.