Pleymor Pleymor - 27 days ago 10
Javascript Question

Transform a deep JSON to an array of key/value properties in JavaScript

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

JSON

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


Array of properties

[
"foo.bar.baz": "UP"
]


One-level solution



My current code only treat 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

Answer

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))

Comments