Simon Breton Simon Breton - 2 months ago 10
Javascript Question

Simple array object from nested object in javascript

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.

Answer

Try this one buddy ! As you said you are beginner I did a basic looping please go through the code. This code will loop through dynamic one level nested object. As per your condition of "values"

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 = {};
   for (var key in currentObj) {
      if (key == 'values') {
        for (var deepkey in currentObj[key]) {
          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}];

Demo link : https://jsbin.com/nojafo/6/edit?html,js,console

Comments