Im trying to understand something seemingly incredibly simple.
console.log(${key}: ${value}
) - works so long as return below is commented out.
Once, the 'return' statement is included below it, the function doesn't work and only returns the first key-val of the list.
It returns: a: something
Why is it that console.log(${key}: ${value}
) and
Return (${key}: ${value}
) can be so different and how can I reformat to output the full key/value list from the function? My expected result is: "a: somestring, b: 42,c: false"
Thanks!
const object1 = {
a: "somestring",
b: 42,
c: false,
};
const defineKeyValPairs = (data) => {
console.log(data); //outputs: {a: 'some string', b: 42, c: false}
for (const [key, value] of Object.entries(data)) {
console.log(`${key}: ${value}`); // returns "a: somestring, b: 42,c: false" so long as return below is commented out
// return `${key}: ${value}`; // doesn't work - returns "a: somestring"
}
};
defineKeyValPairs(object1);
Thank you @Konrad, @epascarello and @Ivar for the direction.
Here's the solution:
const defineKeyValPairs = (data) => {
console.log(data);
return (Object.entries(data).map(([key, value]) => {
return `${key}: ${value}`;
}))
};
defineKeyValPairs(object1);
Returns: a: somestring, b: 42,c: false as the question requested. Hopefully this helps someone else out.