Reputation: 87
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?
Upvotes: 3
Views: 1248
Reputation: 31712
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);
Upvotes: 3
Reputation: 131
use console.log instead of return. When you return the function stops running or maybe you want to use another function.
Upvotes: 0