The initial array I have is pulled from a spreadsheet api so it comes like rows, looking like that
example : Array [
Object {
"brand": "Dell",
"model": "Precision",
},
Object {
"brand": "Apple",
"model": "iMac Pro",
},
Object {
"brand": "Apple",
"model": "MacBook Pro",
},
Object {
"brand": "HP",
"model": "Z840",
},
Object {
"brand": "Apple",
"model": "MacBook Pro",
},
Object {
"brand": "Apple",
"model": "iMac",
},
]
My goal is to convert it like the example below so I can use the data on cascading dropdowns
const data = [
{ brand: 'Brand A', models: [ 'model a1', 'model a2', 'model a3' ] },
{ brand: 'Brand B', models: [ 'model b1', 'model b2', 'model b3' ] },
{ brand: 'Brand C', models: [ 'model c1', 'model c2', 'model c3' ] },
{ brand: 'Brand D', models: [ 'model d1', 'model d2', 'model d3' ] },
];
Initially I don't know the brands and models so the list generated without any input from me, the logic I have implemented is ok except the last line, I couldn't figure out how to push the data in the specific way I demonstrated
console.log("example :", example);
var output = [];
var brands = example
.map((value) => value.brand)
.filter((value, index, _arr) => _arr.indexOf(value) == index);
console.log("brands :", brands);
for (let x in example) {
for (let y in brands) {
console.log(brands[y]);
if (brands[y] === example[x].brand) {
output.push({
brands[y] : example[x].model
// error let y: string (not working)
})
}
}
}