It's pretty simple. I have this :
[{"key":"jim","values":{"count":2,"total":79}},
{"key":"carl","values":{"count":1,"total":120}},
{"key":"stacy","values":{"count":3,"total":90}}]
and I would like this :
[{ "key": 'jim', count: 2, total: 79 },
{ "key": 'carl', count: 1, total: 120},
{ "key": 'stacy', count:3, total: 90}];
I've read stuff about nested object, and other kind of data manipulation with Javascript but I can't solve my issue. I guess I need to use .map
method but I can't make it work. thanks.
Try this one buddy ! As you said you are beginner I did a basic looping with step by step implementation please go through the code. This code will work for dynamic one level nested object.
var arr = [{"key":"jim","values":{"count":2,"total":79}},
{"key":"carl","values":{"count":1,"total":120}},
{"key":"stacy","values":{"count":3,"total":90}}]
var newArr = [];
for (var i = 0; i < arr.length; i++) {
var currentObj = arr[i];
var Obj = {}; // Temporary object
for (var key in currentObj) {
if (typeof currentObj[key] === 'object') { // If it is nested object
for (var deepkey in currentObj[key]) { // Loop again
Obj[deepkey] = currentObj[key][deepkey];
}
}
else {
Obj[key] = currentObj[key];
}
}
newArr.push(Obj);
}
console.log(newArr); // [{ "key": 'jim', count: 2, total: 79 },
{ "key": 'carl', count: 1, total: 120},
{ "key": 'stacy', count:3, total: 90}];
Will work for different inputs
var arr = [{"key":"jim", "hey": {"ting": "bing"} ,"values": {"count":2,"total":79}},
{"key":"carl","values":{"count":1,"total":120}},
{"key":"stacy","values":{"count":3,"total":90}}]
Dynamic one level nested objects
Demo link : https://jsbin.com/nojafo/6/edit?html,js,console
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments