如何遍历JavaScript对象?

Time and again you may feel the need to traverse through an object to find out a particular property, a certain value corresponding to a key or maybe make changes to that object's certain key and values. In arrays, it's pretty simple and we have some flexible methods to iterate over them such as the regular for loop, the forEach loop, etc. When it comes to objects, the simplest way to iterate over an object is the for-in loop.

您可能会一次又一次地感到需要遍历一个对象以找出特定的属性,与某个键对应的某个值,或者可能对该对象的某些键和值进行更改。 在数组中,这非常简单,我们有一些灵活的方法可以对其进行迭代,例如常规的for循环,forEach循环等。涉及对象时,最简单的对象迭代方法是for-in循环。

Consider the following object,

考虑以下对象,

const student1={
	name: 'Ryan',
	age: 15,
	subject: 'Science',
	rank: 17
}
console.log(student1);

Output

输出量

{name: "Ryan", age: 15, subject: "Science", rank: 17}

We can use the for-in loop to iterate over the properties or the keys of our student1 object. Inside the loop, we'll first check if the property belongs solely to our object and only then we'll output it and it's value to the console,

我们可以使用for-in循环来迭代Student1对象的属性或键。 在循环内部,我们将首先检查该属性是否仅属于我们的对象,然后才将其输出,并将其值输出到控制台,

function iterateObj(Obj) {
    for (prop in Obj) {
        if (Obj.hasOwnProperty(prop)) {
            console.log(`${prop} : ${Obj[prop]}`)
        }
    }
}
iterateObj(student1);

Output

输出量

name : Ryan
age : 15
subject : Science
rank : 17

This is a simple way to iterate over the object. We can also use the for-in loop to only print the keys, the values or both key-values as we did above.

这是迭代对象的简单方法。 我们也可以使用for-in循环来仅打印键,值或两个键值,就像我们之前所做的那样。

Looping through an object sounds unconventional because we generally associate iterating over an element with an array. ES6 introduced three methods that we can use which help us converting the object into an array and then we can easily loop through it the way we'd do in an array.

遍历对象听起来是不合常规的,因为我们通常将元素迭代与数组相关联。 ES6引入了三种可用于将对象转换为数组的方法,然后我们可以像在数组中那样轻松地遍历对象。

We can use Object.keys() to convert all our keys of the object into an array of keys.

我们可以使用Object.keys()将对象的所有键转换为键数组。

const studKeys = Object.keys(student1);
console.log(studKeys);

Output

输出量

(4) ["name", "age", "subject", "rank"]

We get an array back with some keys inside it. Let's try to loop through it,

我们得到一个带有一些键的数组。 让我们尝试遍历它,

studKeys.forEach(k => console.log(k));

Output

输出量

name
age
subject
rank

Similarly, we can get an array with all the values of our object using Object.values() method,

同样,我们可以使用Object.values()方法获得包含对象所有值的数组,

const studVal = Object.values(student1);
console.log(studVal);

Output

输出量

(4) ["Ryan", 15, "Science", 17]

And again, we can iterate over this array using a normal for loop too.

再一次,我们也可以使用普通的for循环遍历此数组。

for (let i = 0; i < studVal.length; i++) {
    console.log(studVal[i]);
}

Output

输出量

Ryan
15
Science
17

But what if we want both the key and it's corresponding value together as a pair inside an array? It'd be great if we could have an array of arrays for this, then we'd easily loop overusing the forEach loop.

但是,如果我们想同时将键及其对应的值作为一个数组中的一对配对在一起呢? 如果可以为此提供一个数组数组,那将是非常不错的,然后我们可以轻松地循环使用forEach循环。

We can simply use the Object.entries() method which converts the key-value pairs into individual arrays and combines them or wraps them together inside another array.

我们可以简单地使用Object.entries()方法 ,该方法将键值对转换为单个数组,并将其组合或将它们包装在另一个数组中。

const student = Object.entries(student1);
console.log(student);

Output

输出量

(4) [Array(2), Array(2), Array(2), Array(2)]
    0: (2) ["name", "Ryan"]
    1: (2) ["age", 15]
    2: (2) ["subject", "Science"]
    3: (2) ["rank", 17]
    length: 4
    __proto__: Array(0)

We now get an array with another array having the key and value as separate elements for each index. We can get to any key-value property using the first indexing and use the 0th index to get the key and 1st index to get its value. Let's use the forEach method to loop or iterate over the object that we just converted into a 2D array.

现在,我们得到一个数组,其中另一个数组的键和值作为每个索引的单独元素。 我们可以使用第一个索引获取任何键值属性,并使用0th索引获取键,使用1st索引获取其值。 让我们使用forEach方法来循环或迭代刚刚转换为2D数组的对象。

student.forEach(s => console.log(`${s[0]} : ${s[1]}`));

Output

输出量

name : Ryan
age : 15
subject : Science
rank : 17

Thus we can either use the for-in loop to iterate over an object or first convert it into an array and then iterate over the object as if we're iterating over an array.

因此,我们可以使用for-in循环在对象上进行迭代,也可以先将其转换为数组,然后在对象上进行迭代,就像在数组上进行迭代一样。

翻译自: https://www.includehelp.com/code-snippets/how-to-iterate-over-a-javascript-object.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值