Sukumar Dhoni Sukumar Dhoni - 2 days ago 5
AngularJS Question

Convert json object in to array to iterate through ng-repeat using Javascript

here is my json, i am getting my json obj from firebase i have to convert the list in to array to bind in html trough ng-repeat.

my Json object is



{
"cats1": {
"Name": "cricket",
"imgUrl": "some url",
"list1": {
"bat": {
"Name": "bat",
"imgUrl": "some url",
"price": "$100"
},
"pads": {
"displayName": "pads",
"imgUrl": "some url",
"price": "$50"
}
}
},
"cats2": {
"Name": "football",
"imgUrl": "some url"
}
}


this is how i required



this is the array structure i required , when i add the new list it must store uniquely in cricket category.

[
{
"Name": "cricket",
"imgUrl": "some url",
"list1": [
{
"Name": "bat",
"imgUrl": "some url",
"price": "$100"
},
{
"displayName": "pads",
"imgUrl": "some url",
"price": "$50"
}
]
},
{
"Name": "football",
"imgUrl": "some url"
}
]


i am new to angular any one please help me to figure out this problem

Answer

Use Object.keys and pass them on to Array.prototype.map to create the array that you want - see demo below:

var object={cats1:{Name:"cricket",imgUrl:"some url",list1:{bat:{Name:"bat",imgUrl:"some url",price:"$100"},pads:{displayName:"pads",imgUrl:"some url",price:"$50"}}},cats2:{Name:"football",imgUrl:"some url"}};

var result = Object.keys(object).map(e=>object[e]);

console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}

EDIT:

Correcting the solution to make list1 an array:

var object={cats1:{Name:"cricket",imgUrl:"some url",list1:{bat:{Name:"bat",imgUrl:"some url",price:"$100"},pads:{displayName:"pads",imgUrl:"some url",price:"$50"}}},cats2:{Name:"football",imgUrl:"some url"}};

var result = Object.keys(object).map(function(e){
  Object.keys(object[e]).forEach(function(k){
     if(typeof object[e][k] == "object") {
       object[e][k] = Object.keys(object[e][k]).map(function(l){
         return object[e][k][l];
       });
     }
  });
  return object[e];
});

console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}

Comments