I have an object that looks like this:
myObject = {a: 'hello', b: 2323, c: 123}
I'm trying to loop through and return key and value for each entry with the following function:
returnSomeData(myObject) {
for (const [key, value] of Object.entries(myObject)) {
return (
`${key}: ${value}`
);
}
}
Currently, only the first entry (a: hello) gets returned. Does anyone know why I'm not getting all entries in the object?
You are returning from the first iteration in the for loop. The return statement renders the for loop utterly useless. You should group the results in an array and then return them after the for loop finishes:
returnSomeData(myObject) {
const results = [];
for (const [key, value] of Object.entries(myObject)) {
results.push(
`${key}: ${value}`
);
}
return results;
}
You can also use map like so:
returnSomeData(myObject) {
return Object.entries(myObject).map(([key, value]) => `${key}: ${value}`);
}
Example:
function returnSomeData(myObject) {
return Object.entries(myObject).map(([key, value]) => `${key}: ${value}`);
}
let myObject = {a: 'hello', b: 2323, c: 123};
let result = returnSomeData(myObject);
console.log(result);
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