Reputation: 3706
So I have one of two questions. How can I either manipulate a JSON string data structure in javascript so that from
[
{
"Name":"A170",
"Values":{
"Level 1":1,
"Level 2":22,
"Level 3":22,
"Level 4":1
}
},
{
"Name":"A220",
"Values":{
"Level 1":2,
"Level 2":1,
"Level 3":1,
"Level 4":1
}
}
]
I get this structure instead?
[
{
"Name":"A170",
"Level 1":1,
"Level 2":22,
"Level 3":22,
"Level 4":1
},
{
"Name":"A220",
"Level 1":2,
"Level 2":1,
"Level 3":1,
"Level 4":1
}
]
Or my alternate question would be how to modify the d3 grouped data chart code to make it work with the first data structure. Here's what I have so far that works fine with the second (desired) data structure: http://jsbin.com/tutigaxevo/edit?js,output All help is appreciated. I am not much of a JS guy.
Upvotes: 0
Views: 210
Reputation: 1670
Manipulating a JSON string data structure can be done this way.
var myJson = [
{
"Name":"A170",
"Values":{
"Level 1":1,
"Level 2":22,
"Level 3":22,
"Level 4":1
}
},
{
"Name":"A220",
"Values":{
"Level 1":2,
"Level 2":1,
"Level 3":1,
"Level 4":1
}
}
];
myJson = myJson.map(function(value) {
var tempObj = value;
Object.keys(value).forEach(function(key){
if (typeof value[key] === 'object') {
Object.keys(value[key]).forEach(function(val) {
tempObj[val] = value[key][val];
});
delete tempObj[key];
}
})
return tempObj;
});
console.log(myJson);
Upvotes: 1