简体   繁体   中英

What is the difference between iterating between an object's properties and an array Javascript

I am having trouble understanding the difference between iterating through an array vs. iterating through an object's properties.

What is the difference between:

for (key in object) {
DO THIS
} --> for objects

and

for (var i = 0 ; i<array.length ; i++) {
DO THIS
} --> for arrays

If I want to compare the properties of an object to the values in an array, can I iterate through both the object and the array in the same function. For example, something like this:

for (var key in object){
if (object.hasOwnProperty(key)){
  for (i=0 ; i<array.length; i++){
  if (object[key] === array[i]){   
    filteredKeys[key] = object [key]}

My ultimate goal is to write a function that takes an object and an array of keys and returns a new object with only the keys found in the array.

Objects and arrays are fundamentally different data structures in JavaScript. Objects are collections of key-value pairs, while arrays are ordered lists of data.

Iterating through object keys is different from iterating through an array in that you're accessing data in a different kind of data structure.

My ultimate goal is to write a function that takes an object and an array of keys and returns a new object with only the keys found in the array.

This could be accomplished by doing something like this:

function filterObject(obj, keys) {
  var newObj = {};
  for (var i = 0; i < keys.length; i++) {
    if (keys[i] in obj) {
      newObj[keys[i]] = obj[keys[i]];
    }
  }
  return newObj;
}

For example, calling filterObject({'one': 1, 'two': 2}, ['one', 'three']) will produce the result {'one': 1} .

The thing you have to understand is that arrays are just special objects with properties that are numbers (indicating index) and values indicating elements at those indices -- they have keys and values just like any object. With a for loop like this:

for(var i = 0; i < arr.length; i++) {
  arr[i]; //iterating through the array and accessing each element
}

You're just accessing the the numeric keys like any other object, just through bracket notation because arr.0 is invalid syntax. Now with a for...in loop, you just iterate through the enumerable properties of an object. As I've said, the indices (meaning 0, 1, 2, etc.) to an array are just keys to the array object! Thus, the above for loop does the same as this:

for(var i in arr) {
  arr[i];
}

Because the indices of the array are the keys, this iterates through the keys (indices) and thus you can access elements of the array.


To address your other question -- you can't iterate through an object an array with the same loop if they have different keys. Arrays are ordered with numeric indices as keys, which objects' keys can be anything. Their keys aren't necessarily the same so accessing that key from both the array and object will not yield correct results.

Instead, if you want to filter out certain keys from an object based on if their in an array or not, try the following:

function filterKeysByArray(object, keys) {
  return keys.reduce((filteredObj, key) => {
    if(object.hasOwnProperty(key)) {
      filteredObj[key] = object[key];
    }
    return filteredObj;
  }, {});
}

This completely eliminates the nested for loop. It only ever iterates through the keys in the passed array and reduces it down to a single object, the filtered object. It checks if the object has the property specified by the key, and if it does, it's added to the filtered object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM