Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object.entries loop only returns first entry

Tags:

javascript

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?

like image 501
Patrick1904 Avatar asked Apr 24 '26 16:04

Patrick1904


1 Answers

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);
like image 93
ibrahim mahrir Avatar answered Apr 26 '26 06:04

ibrahim mahrir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!