This simple (as before, I thought) transformation of a JavaScript object defeats me. I would like to flatten this object in the following way.
This is what I have:
{
"1": {
"group": "Clothes",
"brand": {
"0": {
"brand_id": "12",
"brand_name": "Adidas"
},
"1": {
"brand_id": "15",
"brand_name": "Zara"
}
}
},
"2": {
"group": "Cars",
"brand": {
"0": {
"brand_id": "43",
"brand_name": "Ferrari"
},
"1": {
"brand_id": "51",
"brand_name": "BMW"
}
}
}
}
And this is it, what I want to get
{0: {
brand_id: "12",
brand_name: "Adidas",
group: "Clothes",
}
1: {
brand_id: "15",
brand_name: "Zara",
group: "Clothes",
},
2: {
brand_id: "43",
brand_name: "Ferrari",
group: "Cars",
}
3: {
brand_id: "51",
brand_name: "BMW",
group: "Cars",
}}
I tried using .reduce() or .map() but ineffectively.
You can do:
const data = {1: {group: 'Clothes',brand: [{0: {brand_id: '12',brand_name: 'Adidas'}},{1: {brand_id: '15',brand_name: 'Zara'}}]},2: {group: 'Cars',brand: [{0: {brand_id: '43',brand_name: 'Ferrari'}},{1: {brand_id: '51',brand_name: 'BMW'}}]}};
const result = {};
Object.keys(data).forEach(k => {
data[k].brand.forEach((b, i) => {
result[Object.keys(result).length] = {
brand_id: b[i].brand_id,
brand_name: b[i].brand_name,
group: data[k].group
};
});
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
This Object is kind of weird like array-like objects, but index start from 1 not 0, and lack of length.
Fix some typo first, brand should be object not array.
var objectOri = {
1: {
group: 'Clothes',
brand: {
0: {
brand_id: "12",
brand_name: "Adidas"
},
1: {
brand_id: "15",
brand_name: "Zara"
}
}
},
2: {
group: 'Cars',
brand: {
0: {
brand_id: "43",
brand_name: "Ferrari"
},
1: {
brand_id: "51",
brand_name: "BMW"
}
}
}
};
let arr = [];
Object.keys(objectOri).forEach(index => {
let brand = objectOri[index].brand;
Object.keys(brand).forEach(brIndex => {
arr.push({
...brand[brIndex],
group: objectOri[index].group
});
});
});
console.log(Object.assign({}, arr))
Also, if this obejct is a array-like object, the key should start from 0 not 1, and length is also necessary, like below.
var objectOri = {
0: {
group: 'Clothes',
brand: {
0: {
brand_id: "12",
brand_name: "Adidas"
},
1: {
brand_id: "15",
brand_name: "Zara"
},
length: 2
}
},
1: {
group: 'Cars',
brand: {
0: {
brand_id: "43",
brand_name: "Ferrari"
},
1: {
brand_id: "51",
brand_name: "BMW"
},
length: 2
}
},
length: 2
};
let arr = [];
Array.from(objectOri).forEach(item => {
Array.from(item.brand).forEach(brand => {
arr.push({
...brand,
group: item.group
});
});
});
console.log(Object.assign({}, arr))
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