wake-0
wake-0

Reputation: 3966

Iterate object properties from an object array

I have the following array given:

const myArray = [{ id: 1, isSet: true }, { id: 2, isSet: false }, ...];

Actually I want to iterate only the isSet properties of the objects (not all properties). The most simple solution, which came on my mind was the following:

let isSet = false;
for (const obj of myArray) {
    for (const property in obj) {
        if (property === "isSet" && obj.hasOwnProperty(property)) {
            isSet |= obj[property];
        }
    }
}

console.log(isSet);

I think this one does not really look pretty, so has someone a better solution as the given one (maybe also better in runtime)?

Thanks in advance!

Upvotes: 0

Views: 65

Answers (2)

IMTheNachoMan
IMTheNachoMan

Reputation: 5839

You can use the some function of an array.

const myArray1 = [{ id: 1, isSet: false }, { id: 2, isSet: false }, { id: 3, isSet: false }];

let isSet1 = myArray1.some(obj => obj.isSet === true)

console.log(isSet1);

const myArray2 = [{ id: 1, isSet: false }, { id: 2, isSet: true }, { id: 3, isSet: false }];

let isSet2 = myArray2.some(obj => obj.isSet === true)

console.log(isSet2);

Upvotes: 0

mhodges
mhodges

Reputation: 11136

You can do this generically if you pass in your set of rules for each property, like so:

const myArray1 = [{ id: 1, isSet: false }, { id: 2, isSet: false }, { id: 3, isSet: false }];

// check if there is an object with id = 3, isSet = true
var conditions = {
  isSet: (obj) => obj.isSet,
  id: (obj) => obj.id === 3
};
// check if there is an object with id = 2, isSet = false
var conditions2 = {
  isSet: (obj) => !obj.isSet,
  id: (obj) => obj.id === 2
};

function testConditions(arr, conditions) {
  // .some() -- do ANY of the objects match the criteria?
  return arr.some(obj => {
    // .every() -- make sure ALL conditions are true for any given object
    return Object.keys(conditions).every(key => {
      // run comparitor function for each key for the given object
      return conditions[key](obj);
    });
  });
}

console.log(testConditions(myArray1, conditions)); // false -- no object with id = 3, isSet = true
console.log(testConditions(myArray1, conditions2)); // true -- myArray1[1] has id = 2, isSet = false

Upvotes: 2

Related Questions