0

I want to get the data from a JSON file and copy the key and value pair to the array. For example:

jsondata = {
    'Name': {'text': {'name': 'John'}},
    'Age': {'number': {'age': '22'}}
}

in to

array=[["Name","text","name","John"]
       ["Age","number","age","22"]]

Is this possible?

1
  • Looking into the lodash package. I'm pretty sure there's a function for that Commented Jul 28, 2016 at 20:58

2 Answers 2

2

In vanilla js it could be something like this:

data = {
    'Name': {'text': {'name': 'John'}},
    'Age': {'number': {'age': '22'}}
}

function linearize(obj) {
    if (typeof obj !== 'object')
        return [obj];
    var res = [];
    for (var key in obj) {
        for (var a of linearize(obj[key])) {
            res.push([key].concat(a))
        }
    }
    return res;
}

r = linearize(data)
console.log(r)

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

3 Comments

This approach assume the nesting is always 2 steps deep, my code assume there is only ever one child per nested object, @javier's code assume you have access to .map and arrow functions, the moral of the story is lodash has probably solved this kind of problem already :)
@JasonSperske: this approach assume the nesting is always 2 steps deep - why?
Totally missed the recursive call in your inner for-loop, my bad. Apparently we were both working on the same approach but yours is more flexible
2

Without using external libraries, you can try:

function concatify (json) {
    return typeof json == "string" ? json : Object.keys(json).reduce((x,y) => x.concat(y).concat(concatify(json[y])), []);
}

Object.keys(jsondata).map(k => [k].concat(concatify(jsondata[k])));

or

Object.keys(json).map(k => [k].concat(JSON.stringify(json[k]).replace(/["\{\}]/g,'').split(':')))

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.