Here is my sample 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.
{
"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 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
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;}
You can recursion but do note this can cause freeze for big objects and can also lead to Maximum Call Stack exceeded
Object.keys(obj).map(x=>obj[x])
will do.function ObjectToArray(obj) {
if (typeof(obj) === 'object') {
var keys = Object.keys(obj);
var allObjects = keys.every(x => typeof(obj[x]) === 'object');
if (allObjects) {
return keys.map(x => ObjectToArray(obj[x]));
} else {
var o = {};
keys.forEach(x => {
o[x] = ObjectToArray(obj[x])
});
return o;
}
} else {
return obj;
}
}
var d={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"}};
console.log(ObjectToArray(d))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With