I've got values inside array objects and supposed to populate in readable format but stuck as output gets error like "[object Object] undefined".
my desired output is supposed to be like:
Saab - Smodel1,Smodel2,Smodel3, Volvo - Vmodel1,VmodeL2,Vmodel3, BMW - Bmodel1,Bmodel2,Bmodel3,
here is my code:
const cars = [{
"Saab":["Smodel1", "Smodel2", "Smodel3"],
"Volvo":["Vmodel1", "Vmodel2", "Vmodel3"],
"BMW":["Bmodel1", "Bmodel2", "Bmodel3"]
}];
let car_model = '';
for(let i = 0; i < cars.length; i++) {
car_model += cars[i] + "-" + cars[i][i] + "<br/>";
}
added for reference
var cars =
var car, hash;
for (var model in cars) {
car = key;
hash = cars[key];
get(car, hash);
seen(car, hash);
(function loop(car, hash) {
setTimeout(function () {
get(car, hash);
loop(car, hash);
}, 1000);
})(car, hash);
}
Current output: [object Object] undefined
You can loop over the only single object in your array using Object.entries(...) and then Array.map(...) the values to the desired strings. String.join(...) will also be of great help, as it allows you to easily join an array to a single string, with a given seperator.
const cars = [{
"Saab":["Smodel1", "Smodel2", "Smodel3"],
"Volvo":["Vmodel1", "Vmodel2", "Vmodel3"],
"BMW":["Bmodel1", "Bmodel2", "Bmodel3"]
}];
console.log(
Object
.entries(cars[0]) // take your first (and only) element and split it into key value pairs
.map(([key, values]) => // map the key value pairs
`${key} - ${values.join(",")}` // to the desired output format
)
.join(",") // join the mapped values by a ,
)
const cars = {
"Saab":["Smodel1", "Smodel2", "Smodel3"],
"Volvo":["Vmodel1", "Vmodel2", "Vmodel3"],
"BMW":["Bmodel1", "Bmodel2", "Bmodel3"]
};
car_models = '';
for (let i=0; i < Object.keys(cars).length; i ++) {
models = cars[Object.keys(cars)[i]];
car_models += Object.keys(cars)[i] + " " + models.join();
}
Outputs
Saab Smodel1,Smodel2,Smodel3Volvo Vmodel1,Vmodel2,Vmodel3BMW Bmodel1,Bmodel2,Bmodel3
If you want to use only traditional for-loops
const cars = [{
"Saab":["Smodel1", "Smodel2", "Smodel3"],
"Volvo":["Vmodel1", "Vmodel2", "Vmodel3"],
"BMW":["Bmodel1", "Bmodel2", "Bmodel3"]
}];
let car_model = '';
for(let i = 0; i < cars.length; i++) {
const brands = Object.keys(cars[i]);
for (let j = 0; j < brands.length; j++) {
const models = cars[i][brands[j]];
for (let k = 0; k < models.length; k++) {
car_model += brands[j] + "-" + models[k] + "<br/>";
}
}
}
console.log(car_model)