0

I have a mapping object in which property and Value looks like below :

var obj = {
     key: "key1.key2.key3.key4"
};

How to convert obj to nested javascript object as shown below:

var returnObj = {
       key1: {
            key2: {
                   key3:{
                        key4: {
                              "value": key
                        }
                   }
            }
       }
};
9
  • Basically that mapping object contains many keys (values as strings).. So accordingly the returnObj will be nested with number of objects inside.. Commented Sep 26, 2017 at 9:03
  • What did you try yourself before posting this question? Commented Sep 26, 2017 at 9:04
  • do you really swap key and value parts? Commented Sep 26, 2017 at 9:07
  • 2
    Why is t his tagged as java? Commented Sep 26, 2017 at 9:08
  • 2
    java != javascript Commented Sep 26, 2017 at 9:09

1 Answer 1

2

You could iterate the keys and then split the string for single properties. Then create objects, if not exists. Later assign the original key as value.

function convert(object) {
    var result = {};
    Object.keys(object).forEach(function (k) {
        object[k].split('.').reduce(function (o, k) {
            return o[k] = o[k] || {};
        }, result).value = k;
    });
    return result;
}

var obj = { key: "key1.key2.key3.key4" };

console.log(convert(obj));
  
.as-console-wrapper { max-height: 100% !important; top: 0; }

With last key as key.

function convert(object) {
    var result = {};
    Object.keys(object).forEach(function (k) {
        var path = object[k].split('.'),
            last = path.pop();
       
        path.reduce(function (o, k) {
            return o[k] = o[k] || {};
        }, result)[last] = k;
    });
    return result;
}

var obj = { key: "key1.key2.key3.key4" };

console.log(convert(obj));
  
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

3 Comments

and if i want to have like this object ->var returnObj = { key1: { key2: { key3:{ key4: key } } } }; how will the above code change?
then you need to save the last splitted value and take it as value , instead of .value =.
Thank you so much!

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.