I have this array :
var res_data = [
{"id": "1", "text": "AAA", "category": "food", "value": "1"},
{"id": "2", "text": "BBB", "category": "food", "value": "2"},
{"id": "3", "text": "CCC", "category": "drinks", "value": "3"}
];
I want to get this
{
"food": [
{
"id": "1",
"text": "AAA",
"category": "food",
"value": "1"
},
{
"id": "2",
"text": "BBB",
"category": "food",
"value": "2"
}
],
"drinks": [
{
"id": "3",
"text": "CCC",
"category": "drinks",
"value": "3"
}
]
}
I've tried to do so by iterating and set the "category" value - as a key , inside a new array, like this :
var res = [];
$.each(obj, function () {
if (this.hasOwnProperty("category")) {
res[this['category']] = this;
console.log(this['category']);
}
})
but the "food" index is keep overriding....
drinks:{id: "3", text: "CCC", category: "drinks", value: "3"}
food: {id: "3", text: "CCC", category: "food", value: "2"}
A common iteration technique when converting an array into another structure is to use reduction:
const arr = [
{"id": "1", "text": "AAA", "category": "food", "value": "1"},
{"id": "2", "text": "BBB", "category": "food", "value": "2"},
{"id": "3", "text": "CCC", "category": "drinks", "value": "3"}
]
const result = arr.reduce((hash, item) => {
if (!hash.hasOwnProperty(item.category)) {
hash[item.category] = []
}
hash[item.category].push(item)
return hash
}, {})
console.log(result)
You can also use forEach for array.
ES5
var arr = [{
"id": "1",
"text": "AAA",
"category": "food",
"value": "1"
},
{
"id": "2",
"text": "BBB",
"category": "food",
"value": "2"
},
{
"id": "3",
"text": "CCC",
"category": "drinks",
"value": "3"
}
],
outpt = {};
arr.forEach(function(item) {
if (!outpt.hasOwnProperty(item.category)) {
outpt[item.category] = []
}
outpt[item.category].push(item)
});
console.log(outpt)
ES6
let arr = [{
"id": "1",
"text": "AAA",
"category": "food",
"value": "1"
},
{
"id": "2",
"text": "BBB",
"category": "food",
"value": "2"
},
{
"id": "3",
"text": "CCC",
"category": "drinks",
"value": "3"
}
],
outpt = {};
arr.forEach((item) => {
if (!outpt.hasOwnProperty(item.category)) {
outpt[item.category] = []
}
outpt[item.category].push(item)
});
console.log(outpt)
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