bumblebee bumblebee - 3 months ago 18
AngularJS Question

Parse Objects and Arrays in Json data in AngularJs

I am trying to build an array of objects using the data I get from backend service using angularjs. Here is how I get the data

"mylist": [

{

"name": "Test1",
"moreInfo": {
"moreInfoText": "More test",
},

"companyInfo": {
"companyNameInfo": "ABC",
"url": "http://www.google.com",

}

},

{

"name": "Test2",
"moreInfo": {
"moreInfoText": "More test2",
},

"companyInfo": {
"companyNameInfo": "ABC2",
"url": "http://www.yahoo.com",
}


},

]


I want to parse it so I can combine it all in one array of objects like

[{"name": "Test1", "moreInfoText": "More test","companyNameInfo": "ABC", "url": "http://www.google.com"},{ "name": "Test2", "moreInfoText": "More test2","companyNameInfo": "ABC2", "url": ""}]

Answer

Try this:

var flatten = function(object) {
    var newObj = {};

    for (var key in object) {
      var item = object[key];
      if (typeof item !== 'object') {
        newObj[key] = item;
      }

      else {
        var flattened = flatten(item);
        for (var k in flattened) {
          newObj[k] = flattened[k];
        }
      }
    }
    return newObj;
};

var newList = [];
myList.forEach(function(object) {
     newList.push(flatten(object);
});
console.log(newList) //this should be what you want