Home > Blockchain >  I can't change a variable value in object.entries foreach from parent scope
I can't change a variable value in object.entries foreach from parent scope

Time:12-28

I want to get a boolean from an Object.entries(b).foreach but I don't know how to retrieve it.

Like :

const body = {a:1,b:2}
function handle() {
  let myBool = true;
  Object.entries(body).forEach(([key, value]) => {
   myBool = false;
  });
  return myBool;
}

So, that's always return true, I tried something like

const body = {a:1,b:2}
function handle() {
  return Object.entries(body).forEach(([key, value]) => {
   return false;
  });
}

But it doesn't work. it's probably a lack of understanding JS, can you give me a hint ?

CodePudding user response:

Unlike Array.prototype.map(), Array.prototype.forEach() always returns undefined and is not chainable. The typical use case is to execute side effects at the end of a chain.

More details here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

CodePudding user response:

In the second version of the handle function, you are returning false inside the callback function of forEach, but that value is not being returned by the handle function itself.

One option to achieve the desired behavior is to use the some array method instead of forEach. The some method will iterate over the array and return true as soon as the callback function returns a truthy value. In this case, you can return false from the callback to make some return true.

Here's an example of how you could modify the handle function to return false if at least one entry in the object has a truthy value:

const body = {a: 1, b: 2}

function handle() {
  return !Object.entries(body).some(([key, value]) => value);
}

console.log(handle()); // prints "false"

Alternatively, you can use a for loop or a for-of loop instead of forEach or some, and use a break statement to exit the loop as soon as you find an entry with a truthy value. Here's an example using a for-of loop:

const body = {a: 1, b: 2}

function handle() {
  for (const [key, value] of Object.entries(body)) {
    if (value) return false;
  }
  return true;
}

console.log(handle()); // prints "false"
  • Related