简体   繁体   English

在对象的属性和数组Javascript之间进行迭代有什么区别

[英]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. 对象和数组是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} . 例如,调用filterObject({'one': 1, 'two': 2}, ['one', 'three'])将产生结果{'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循环:

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. 您就像括号中的数字一样访问数字键,因为arr.0是无效的语法。 Now with a for...in loop, you just iterate through the enumerable properties of an object. 现在有了for ... in循环,您只需遍历对象的可枚举属性。 As I've said, the indices (meaning 0, 1, 2, etc.) to an array are just keys to the array object! 如我所说,数组的索引(意味着0、1、2等)只是数组对象的键! Thus, the above for loop does the same as this: 因此,上面的for循环与此相同:

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. 这完全消除了嵌套的for循环。 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. 它检查对象是否具有键指定的属性,如果包含,则将其添加到过滤的对象中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 除了.length属性外,JavaScript Array和Object有什么区别? - What's the difference between JavaScript Array and Object except .length property? 迭代 object 时,javascript 中的“数字”和数字有什么区别? - What's the difference between “number” and Number in javascript when iterating over an object? JavaScript中的“节点”和“对象”有什么区别? - What's the difference between “node” and “object” in JavaScript? Javascript中的对象属性和对象属性有什么区别? - What is the difference between object properties and object attributes in Javascript? Javascript:|之间有什么区别 和||? - Javascript: what's difference between | and ||? JavaScript 中的 &amp; 和 &amp;&amp; 有什么区别? - What's the difference between & and && in JavaScript? JavaScript 对象和 OO/UML/Java 对象有什么区别? - What's the difference between a JavaScript object and an OO/UML/Java object? Javascript对象和JSON对象之间有什么区别 - What's the difference between Javascript Object and JSON object 声明 JavaScript 数组时,“Array()”和“[]”有什么区别? - What’s the difference between "Array()" and "[]" while declaring a JavaScript array? JavaScript 中的 Array(1) 和 new Array(1) 有什么区别? - What's the difference between Array(1) and new Array(1) in JavaScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM