To compare the keys of an object in an array during a loop, you can use the Object.keys()
method to get an array of keys for each object, and then compare the keys using a loop. Here's an example:
let arr = [
{ name: 'John', age: 27, city: 'New York' },
{ name: 'Sarah', age: 31, city: 'Boston' },
{ name: 'Mike', age: 25, city: 'Chicago' }
];
for (let i = 0; i < arr.length; i++) {
let keys = Object.keys(arr[i]);
for (let j = 0; j < keys.length; j++) {
console.log(keys[j]); // log each key for the current object
// compare each key to some value or perform some action
}
}
In this example, we first loop through the array using a for
loop. For each object in the array, we use the Object.keys()
method to get an array of keys for the current object. We then nest another loop to iterate through each key in the array of keys. Inside this inner loop, we can compare each key to some value or perform some action based on the key.
Asked: 2023-03-27 11:00:00 +0000
Seen: 3 times
Last updated: Apr 07 '22