In my programming challenge, I am dealing with an array of objects that have dynamic keys and values. The structure is a bit complicated, but here's a simplified version:
let products_row = [
{
id: 1,
category_id: 11,
options: {
'modelName1': {
size: '2 feet',
colour: 'red',
is_new: true
},
'modelName2': {
size: '4 feet',
colour: 'black',
is_new: true
},
}
},
// More objects...
]
The desired result format should look like this:
let resultArray = [
{
id: 1,
category_id: 11,
model: 'modelName1',
size: '2 feet',
colour: 'red',
is_new: true
},
// More results...
]
I've attempted to transform the data but encountered some issues. Here's what I tried:
let productsData = [];
products_row.map((product) => Object.entries(product.options || {}).map((model) => {
return productsData.push({
model: model[0],
[Object.keys(product).find(key => !['id', 'category_id'].includes(key))]: product[Object.keys(product).find(key => !['id', 'category_id'].includes(key))],
...model[1]
});
}));
console.log(productsData);
However, the output doesn't include all data as intended. It seems like I'm struggling to retain the previous key-value pairs. Here's the incomplete result:
[
{
model: 'modelName1',
id: 1,
size: '2 feet'
},
// Incomplete results...
]
I'm currently stuck at this point and would appreciate any guidance or assistance. Thank you.