Home > Back-end >  Loop through arrayObjects with condition Javascript
Loop through arrayObjects with condition Javascript

Time:10-24

I found a nice example on here showing how to look through arrayObjects with a condition but I have a question.

As is stands its console.logging every time it the condition is false. Is it possible to only console.log once when its finished looping through everything.

var arrayObjects = [{
    "building": "A",
    "status": "good"
  },
  {
    "building": "B",
    "status": "horrible"
  }
];

for (var i = 0; i < arrayObjects.length; i  ) {
  console.log(arrayObjects[i]);

  for (key in arrayObjects[i]) {

    if (key == "status" && arrayObjects[i][key] == "good") {

      console.log(key   "->"   arrayObjects[i][key]);
    } else {
      console.log("nothing found");
    }
  }
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Simply use .length with if condition.

var arrayObjects = [{
    "building": "A",
    "status": "good"
  },
  {
    "building": "B",
    "status": "horrible"
  }
];

for (var i = 0; i < arrayObjects.length; i  ) {
  console.log(arrayObjects[i]);

  if( i === arrayObjects.length-1 ) {
      console.log("nothing found");
  }
}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

I'm assuming that you want it to print Nothing found when nothing's really found, not even a single thing..

Then, you can try this.


var arrayObjects = [{"building":"A", "status":"good"}, 
{"building":"B","status":"horrible"}];

var isFound = false;

 for (var i=0; i< arrayObjects.length; i  ) {
  console.log(arrayObjects[i]);

   for(key in arrayObjects[i]) {

  if (key == "status" && arrayObjects[i][key] == "good") {
      isFound = true
      console.log(key   "->"   arrayObjects[i][key]);
  }
 }
}

if (isFound === false){
      console.log("nothing found");
  }

CodePudding user response:

If you're open to refactoring your for..in loop, you could use a reduce() to give you the value at the end only.

const foundKeys = arrayObjects[i].reduce((bool, key) => {
    if (key === "status" && arrayObjects[i][key] === "good") {
      console.log(key   "->"   arrayObjects[i][key]);
      bool = true
    }
    return bool 
}, false)

if (!foundKeys) {
    console.log("Nothing found")
}

CodePudding user response:

You can use the some or filter method of array.

var arrayObjects = [{"building":"A", "status":"good"}, 
{"building":"B","status":"horrible"}];

const found = arrayObjects.some(it => it.status === 'good')
if (found) {
  console.log('found')
}

const items = arrayObjects.filter(it => it.status === 'good')
if (items.length) {
  console.log('found')
}
 
  • Related