0

I have a basic json question that is giving me headache since a couple of hours, I am trying to dynamically add keys to a Json object using an array of string.

Here is my array of string:

let key =  ['session', 'view_state', 'footer', 'config', 'items'] 

I have another variable which is jsonValue and is my whole json object. I want to end up with one of those options:

jsonValue.session.view_state.footer.config.items
jsonValue['session']['view_state']['footer']['config']['items']

This is my best attempt using a forEach.

forEach(jsonKeys, (el) => {
  jsonCollection += jsonCollection !== undefined ? '."' +[el + '"'] : [ '"' + el + '"' ];
})

But I have this result: 

undefined"session"."view_state"."footer"."config"."items"

Any help will be appreciated!

4
  • 1
    If it's undefined, you don't want to append. Commented Nov 21, 2017 at 22:16
  • need more code, not clearer enought Commented Nov 21, 2017 at 22:19
  • What is the end result you are after? How will you use this object stricture? Do you want jsonValue.session.view_state.footer.config.items to be a specific value? an object, an Array, something else?? Or are you trying to pass in the array to get at a specific value from your object? Commented Nov 21, 2017 at 22:32
  • I am trying to pass the array to get a specific value from my Json object, yes. Whether it is a string on another array Commented Nov 21, 2017 at 22:41

1 Answer 1

3

To get a value using the keys array

Iterate with Array#reduce, check the type of the current value, if it's an object, return the value of the key, if not return undefined:

const obj = {
  "demo": true,
  "session": {
    "view_state": {
      "footer": {
        "config": {
          "items": [
            1,
            2
          ]
        }
      }
    }
  }
};

const keys =  ['session', 'view_state', 'footer', 'config', 'items'];

const value = keys.reduce((val, key) => val && typeof val === 'object' ?
  val[key] : undefind, obj);

console.log(value);

To add a value using the keys array

Use Array#reduceRight to create a chain of objects with the value you want. Use Object#assign to update the original object with the results:

const keys =  ['session', 'view_state', 'footer', 'config', 'items'];

const obj = { demo: true };

Object.assign(obj, keys.reduceRight((val, key) => ({ [key]: val }), [1, 2])); // replace [1, 2] with the actual items

console.log(obj);

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

3 Comments

Wow, Array#reduceRight .. what a fascinating bit of code. Nice answer!
very elegant solution ;-)
Short and neat! Thank you

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.