0

I want to generate a dynamic object and assign value into it. Following is the code

var chunk = "INTERNATIONALISATION#LANGUAGE#DICTIONARY#EN";
var c = chunk.split('#');
var a = {};

So the output should be like this

a["INTERNATIONALISATION"]["LANGUAGE"]["DICTIONARY"]["EN"] = 10;

Tried looping through array but nothing works for now.Please advise.

1
  • What does not work exactly? Commented Dec 26, 2017 at 10:12

1 Answer 1

7

Try this:

var chunk = "INTERNATIONALISATION#LANGUAGE#DICTIONARY#EN";
var c = chunk.split('#');
var a = {};
var lastKey = c.pop();
c.reduce((obj, key) => obj[key] = obj[key] || {}, a)[lastKey] = 10;

To make it more convenient you can put it in a function:

const dynamicAssign = (object, stringPath, value) => {
    const path = stringPath.split('#');
    const lastKey = path.pop();
    const target = path.reduce((obj, key) => obj[key] = obj[key] || {}, object);
    target[lastKey] = value;
};

const a = {};
dynamicAssign(a, "INTERNATIONALISATION#LANGUAGE#DICTIONARY#EN", 10);
Sign up to request clarification or add additional context in comments.

4 Comments

1+ short and perfect!
Why would you use a dynamic "object generator" if you then assign a value to one of its properties by hand? O.o
I cannot assign value directly as a["INTERNATIONALISATION"]["LANGUAGE"]["DICTIONARY"]["EN"] = 10.
@Andreas, my answer was answering what the OP asked for.. I couldn't assume that this wasn't what he really wanted :)

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.