4

How to turn a JSON To a properties array in JS, no matter what's the JSON's depth ?

JSON

{
    "foo": {
        "bar": {
            "baz": "UP"
        }
    }
}

key/value properties

{
  "foo.bar.baz": "UP"
}

One-level solution

My current code only treats one level, instead of n:

var user = {name: 'Corbin', age: 20, location: 'USA'},
    key;

for (key in user) {
    if (user.hasOwnProperty(key)) {
        console.log(key + " = " + user[key]);
    }
}

Thank you :D

4
  • Please post your existing code and explain what is wrong with it. Commented Nov 7, 2016 at 10:14
  • Thank you @Archer, I've updated my question as you suggested it to me. My current solution doesn't cover any JSON depth, that's my problem. Commented Nov 7, 2016 at 10:39
  • That's not JSON Commented Nov 7, 2016 at 10:43
  • Thanks @naomik, my bad ! fixed now Commented Nov 7, 2016 at 10:50

1 Answer 1

4

Basically, if a member is an object, make a recursive call, otherwise, update the output object:

data = {
    foo: "hello",
    bar: {
        baz: {
            qux: "UP"
        },
        spam: 'ham'
    }
}



function unwrap(obj, prefix) {

    var res = {};

    for (var k of Object.keys(obj)) {
        var val = obj[k],
            key = prefix ? prefix + '.' + k : k;

        if (typeof val === 'object')
            Object.assign(res, unwrap(val, key)); // <-- recursion
        else
            res[key] = val;
    }

    return res;
}

console.log(unwrap(data))

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

Comments

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.