我在JavaScript中有一个对象:

{
    abc: '...',
    bca: '...',
    zzz: '...',
    xxx: '...',
    ccc: '...',
    // ...
}

我想用一个for循环来获取它的属性。我想要迭代它的部分(不是所有的对象属性一次)。

对于一个简单的数组,我可以用一个标准的for循环来做:

for (i = 0; i < 100; i++) { ... } // first part
for (i = 100; i < 300; i++) { ... } // second
for (i = 300; i < arr.length; i++) { ... } // last

但是如何对对象进行处理呢?


当前回答

在参数中定义object,避免选择器和下标

有许多语法选择,但这个在闭包的参数中定义了前面的对象,从而消除了迭代器中选择器或下标的需要。K是键,v是值,I是索引。

const obj = {
    kiwi: true,
    mango: false,
    pineapple: 500
};

Object.entries(obj).forEach(([k, v], i) => {
    console.log(k, v, i);
});

// kiwi true 0
// mango false 1
// pineapple 500 2

其他回答

var Dictionary = {
  If: {
    you: {
      can: '',
      make: ''
    },
    sense: ''
  },
  of: {
    the: {
      sentence: {
        it: '',
        worked: ''
      }
    }
  }
};

function Iterate(obj) {
  for (prop in obj) {
    if (obj.hasOwnProperty(prop) && isNaN(prop)) {
      console.log(prop + ': ' + obj[prop]);
      Iterate(obj[prop]);
    }
  }
}
Iterate(Dictionary);

->如果我们遍历一个JavaScript对象使用并找到数组的键 对象

Object.keys(Array).forEach(key => {

 console.log('key',key)

})

使用对象。你这样做。

 // array like object with random key ordering
 const anObj = { 100: 'a', 2: 'b', 7: 'c' };
 console.log(Object.entries(anObj)); // [ ['2', 'b'],['7', 'c'],['100', 'a'] ]

object .entries()方法返回给定对象自身可枚举属性[key, value]的数组。

你可以遍历对象每个对象都有键和值,得到这样的东西。

const anObj = { 100: 'a', 2: 'b', 7: 'c' };
Object.entries(anObj).map(obj => {
   const key   = obj[0];
   const value = obj[1];

   // do whatever you want with those values.
});

或者像这样

// Or, using array extras
Object.entries(obj).forEach(([key, value]) => {
  console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
});

参考MDN文档中的对象条目

<script type="text/javascript">
// method 1
var images = {};
images['name'] = {};
images['family'] = {};
images[1] = {};
images['name'][5] = "Mehdi";
images['family'][8] = "Mohammadpour";
images['family']['ok'] = 123456;
images[1][22] = 2602;
images[1][22] = 2602;
images[1][22] = 2602;
images[1][22] = 2602;
images[1][23] = 2602;

for (const [key1, value1] of Object.entries(images)){
    for (const [key2, value2] of Object.entries(value1)){
        console.log(`${key1} => ${key2}: ${value2}`);
    }
}


console.log("=============================");

// method 2
var arr = [];
for(var x = 0; x < 5; x++){
     arr[x] = [];    
     for(var y = 0; y < 5; y++){ 
         arr[x][y] = x*y;    
     }    
 }

for(var i = 0; i < arr.length; i++) {
    var cube = arr[i];
    for(var j = 0; j < cube.length; j++) {
        console.log("cube[" + i + "][" + j + "] = " + cube[j]);
    }
}

</script>

你可以尝试使用lodash-一个现代的JavaScript实用程序库,提供模块化,性能和额外的js来快速对象迭代

var  users  =   { 'fred':     {  'user':   'fred',     'age':  40  }, 'pebbles':  {  'user':   'pebbles',  'age':  1  } };  _.mapValues(users,  function(o)  {  return  o.age;  }); // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) // The `_.property` iteratee shorthand. console.log(_.mapValues(users,  'age')); // returns age property & value console.log(_.mapValues(users,  'user')); // returns user property & value console.log(_.mapValues(users)); // returns all objects // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash-compat/3.10.2/lodash.js"></script>