Zach Conn
Zach Conn

Reputation: 1311

Treating JSON as a tree structure

I have some incoming JSON which consists of only nested maps (no arrays), e.g.,

{
    "name1": {
        "name2": "name3",
        "name4": {
            "name5": "name6"
        }
    },
    "name7": "name8"
}

Notice that the keys and values here don't follow any particular pattern.

What I want is, given such an object representing the root of a tree, to produce a list of new objects representing the first layer of children, each as a new JSON object.

Upvotes: 1

Views: 192

Answers (2)

user1987630
user1987630

Reputation:

function ent(map) {
  var entries = [];
  for (var key in map) 
    entries.push({
      key: key,
      value: map[key]
    });
  return entries;
}

ent({
  "name1": {"name2": "name3", "name4": {"name5": "name6"}},
  "name7": "name8"
})

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

Something like

var obj = {
    "name1": {"name2": "name3", "name4": {"name5": "name6"}},
    "name7": "name8"
}

var result = [], tmp;
for(var key in obj){
    if(obj.hasOwnProperty(key)){
        tmp = {};
        tmp[key] = obj[key];
        result.push(tmp)
    }
}
console.log(result)

Demo: Fiddle

Upvotes: 2

Related Questions