如何遍历JavaScript对象?

2020/09/27 05:21 · javascript ·  · 0评论

我在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

但是如何处理对象呢?

对于大多数对象,请使用for .. in

for (let key in yourobject) {
  console.log(key, yourobject[key]);
}

使用ES6,如果同时需要键和值,请执行

for (let [key, value] of Object.entries(yourobject)) {
    console.log(key, value);
}

为了避免记录继承的属性,请使用hasOwnProperty进行检查

for (let key in yourobject) {
   if (yourobject.hasOwnProperty(key)) {
      console.log(key, yourobject[key]);
   }
}

hasOwnProperty如果您使用的是简单的对象(例如,您自己创建的对象),则无需在迭代键时进行检查{}

该MDN文档更一般地说明了如何处理对象及其属性。

如果要“分块”执行,最好的方法是将键提取到数组中。由于不能保证订购,因此这是正确的方法。在现代浏览器中,您可以使用

let keys = Object.keys(yourobject);

为了更加兼容,您最好这样做:

 let keys = [];
 for (let key in yourobject) {      
     if (yourobject.hasOwnProperty(key)) keys.push(key);
 }

然后,您可以按索引访问属性yourobject[keys[i]]

for (let i=300; i < keys.length && i < 600; i++) { 
   console.log(keys[i], yourobject[keys[i]]);
}

这是现代浏览器的另一个迭代解决方案:

Object.keys(obj)
  .filter((k, i) => i >= 100 && i < 300)
  .forEach(k => console.log(obj[k]));

或不带过滤功能:

Object.keys(obj).forEach((k, i) => {
    if (i >= 100 && i < 300) {
        console.log(obj[k]);
    }
});

但是,您必须考虑JavaScript对象中的属性未排序,即没有顺序。

Object.entries你做这样的事情。

 // 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]的数组

所以,你可以遍历对象,并有keyvalue每个对象,并得到这样的事情。

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文档

借助新的ES6 / ES2015功能,您不再需要使用对象来遍历哈希。您可以使用MapJavascript Maps将键按插入顺序保留,这意味着您可以遍历它们而不必检查hasOwnProperty,这始终是一个hack。

遍历地图:

var myMap = new Map();
myMap.set(0, "zero");
myMap.set(1, "one");
for (var [key, value] of myMap) {
  console.log(key + " = " + value);
}
// Will show 2 logs; first with "0 = zero" and second with "1 = one"

for (var key of myMap.keys()) {
  console.log(key);
}
// Will show 2 logs; first with "0" and second with "1"

for (var value of myMap.values()) {
  console.log(value);
}
// Will show 2 logs; first with "zero" and second with "one"

for (var [key, value] of myMap.entries()) {
  console.log(key + " = " + value);
}
// Will show 2 logs; first with "0 = zero" and second with "1 = one"

或使用forEach:

myMap.forEach(function(value, key) {
  console.log(key + " = " + value);
}, myMap)
// Will show 2 logs; first with "0 = zero" and second with "1 = one"

如果在迭代时需要键和值,则可以Object.entries使用for ... of循环

const myObj = {a: 1, b: 2}

for (let [key, value] of Object.entries(myObj)) {
    console.log(`key=${key} value=${value}`)
}

// output: 
// key=a value=1
// key=b value=2

唯一可靠的方法是将对象数据保存到2个数组中,其中之一是键,另一个用于数据:

var keys = [];
var data = [];
for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        keys.push(key);
        data.push(obj[key]); // Not necessary, but cleaner, in my opinion. See the example below.
    }
}

然后,您可以像通常那样遍历数组:

for(var i = 0; i < 100; i++){
    console.log(keys[i], data[i]);
    //or
    console.log(keys[i], obj[keys[i]]); // harder to read, I think.
}
for(var i = 100; i < 300; i++){
    console.log(keys[i], data[i]);
}

我没有使用Object.keys(obj),因为那是IE 9+。

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

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

 console.log('key',key)

})

如果要一次迭代整个对象,可以使用for in循环:

for (var i in obj) {
  ...
}

But if you want to divide the object into parts in fact you cannot. There's no guarantee that properties in the object are in any specified order. Therefore, I can think of two solutions.

First of them is to "remove" already read properties:

var i = 0;
for (var key in obj) {
    console.log(obj[key]);
    delete obj[key];
    if ( ++i > 300) break;
}

Another solution I can think of is to use Array of Arrays instead of the object:

var obj = [['key1', 'value1'], ['key2', 'value2']];

Then, standard for loop will work.

I finally came up with a handy utility function with a unified interface to iterate Objects, Strings, Arrays, TypedArrays, Maps, Sets, (any Iterables).

const iterate = require('@a-z/iterate-it');
const obj = { a: 1, b: 2, c: 3 };

iterate(obj, (value, key) => console.log(key, value)); 
// a 1
// b 2
// c 3

https://github.com/alrik/iterate-javascript

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

var  users  =   {
    'fred':     { 
        'user':   'fred',
            'age':  40 
    },
    'pebbles':  { 
        'user':   'pebbles',
         'age':  1 
    }
}; 
_.mapValues(users,  function(oreturn  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>

对于对象迭代,我们通常使用for..in循环。此结构将遍历所有可枚举的属性,包括通过原型继承继承的属性。例如:

let obj = {
  prop1: '1',
  prop2: '2'
}

for(let el in obj) {
  console.log(el);
  console.log(obj[el]);
}

但是,for..in它将遍历所有可枚举的元素,这将使我们无法将迭代拆分为多个块。为此,我们可以使用内置Object.keys()函数来检索数组中对象的所有键。然后,我们可以将迭代分为多个for循环,并使用keys数组访问属性。例如:

let obj = {
  prop1: '1',
  prop2: '2',
  prop3: '3',
  prop4: '4',
};

const keys = Object.keys(obj);
console.log(keys);


for (let i = 0; i < 2; i++) {
  console.log(obj[keys[i]]);
}


for (let i = 2; i < 4; i++) {
  console.log(obj[keys[i]]);
}

如果您有一个简单的对象,则可以使用以下代码遍历该对象:

let myObj = {
  abc: '...',
  bca: '...',
  zzz: '...',
  xxx: '...',
  ccc: '...',
  // ...
};

let objKeys = Object.keys(myObj);

//Now we can use objKeys to iterate over myObj

for (item of objKeys) {
  //this will print out the keys
  console.log('key:', item);
  
  //this will print out the values 
  console.log('value:', myObj[item]);
}

如果您有一个嵌套对象,则可以使用以下代码对其进行迭代:

let b = {
  one: {
    a: 1,
    b: 2,
    c: 3
  },
  two: {
    a: 4,
    b: 5,
    c: 6
  },
  three: {
    a: 7,
    b: 8,
    c: 9
  }
};

let myKeys = Object.keys(b);

for (item of myKeys) {
  //print the key
  console.log('Key', item)
  
  //print the value (which will be another object)
  console.log('Value', b[item])
  
  //print the nested value
  console.log('Nested value', b[item]['a'])
}

如果您有对象数组,则可以使用以下代码对其进行迭代:

let c = [
{
  a: 1,
  b: 2
},
{
  a: 3,
  b: 4
}
];

for(item of c){
//print the whole object individually 
console.log('object', item);

//print the value inside the object
console.log('value', item['a']);
}
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);

确实是PITA,这不是标准Javascript的一部分。

/**
 * Iterates the keys and values of an object.  Object.keys is used to extract the keys.
 * @param object The object to iterate
 * @param fn (value,key)=>{}
 */
function objectForEach(object, fn) {
    Object.keys(object).forEach(key => {
        fn(object[key],key, object)
    })
}

注意:我将回调参数切换为(value,key),并添加了第三个对象以使该API与其他API一致。

这样使用

const o = {a:1, b:true};
objectForEach(o, (value, key, obj)=>{
    // do something
});

是。您可以使用for循环遍历对象。这是一个例子

var myObj = {
    abc: 'ABC',
    bca: 'BCA',
    zzz: 'ZZZ',
    xxx: 'XXX',
    ccc: 'CCC',
}

var k = Object.keys (myObj);
for (var i = 0; i < k.length; i++) {
    console.log (k[i] + ": " + myObj[k[i]]);
}

注意:上述示例仅在IE9 +中有效。请参阅此处的 Objec.keys浏览器支持

const o = {
  name: "Max",
  location: "London"
};

for (const [key, value] of Object.entries(o)) {
  console.log(`${key}: ${value}`);
}

在线尝试

这是一个手工制作的解决方案:

function iterationForObject() {
    let base = 0,
        Keys= Object.keys(this);
    return {
        next: () => {
            return {
                value: {
                    "key": Keys[base],
                    "value": this[Keys[base]]
                },
                done: !(base++ < Keys.length)
            };
        }
    };
}
Object.prototype[Symbol.iterator] = iterationForObject;

然后,您可以循环播放任何对象:

for ( let keyAndValuePair of (Object Here) ) {
    console.log(`${keyAndValuePair.key} => ${keyAndValuePair.value}`);
}
<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>
本文地址:http://javascript.askforanswer.com/ruhebianlijavascriptduixiang.html
文章标签: ,   ,   ,   ,  
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!