Javascript JSON forEach 获取键和值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32751411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:10:11  来源:igfitidea点击:

JSON forEach get Key and Value

javascript

提问by gespinha

I have the following forEachloop over a JSON object called obj:

我在forEach名为 的 JSON 对象上有以下循环obj

Object.keys(obj).forEach(function(){
});

How can I make it console.logboth keyand valueof each item inside the object? Something like this:

我怎样才能使console.log双方keyvalue对象内部的每一个项目的?像这样的东西:

Object.keys(obj).forEach(function(k, v){
    console.log(k + ' - ' + v);
});

Is this possible?

这可能吗?

回答by Josiah Keller

Use index notation with the key.

对键使用索引符号。

Object.keys(obj).forEach(function(k){
    console.log(k + ' - ' + obj[k]);
});

回答by EnzoTrompeneers

Loop through object with arrow functions

使用箭头函数循环遍历对象

ES6

ES6

Object.keys(myObj).forEach(key => {
    console.log(key + ' - ' + myObj[key]) // key - value
})

ES7

ES7

Object.entries(myObj).forEach(([key, value]) => {
    console.log(key + ' - ' value) // key - value
})

ES8

ES8

Loop through objects with ES8 with explanation

使用 ES8 循环遍历对象并附有说明

回答by duncanhall

Assuming that objis a pre-constructed object (and not a JSON string), you can achieve this with the following:

假设这obj是一个预先构造的对象(而不是 JSON 字符串),您可以通过以下方式实现:

Object.keys(obj).forEach(function(key){
   console.log(key + '=' + obj[key]);
});

回答by Paul G

Another easy way to do this is by using the following syntax to iterate through the object, keeping access to the key and value:

另一种简单的方法是使用以下语法遍历对象,保持对键和值的访问:

for(var key in object){
  console.log(key + ' - ' + object[key])
}

so for yours:

所以对于你的:

for(var key in obj){
  console.log(key + ' - ' + obj[key])
}

回答by Joaquín O

Try something like this:

尝试这样的事情:

var prop;
for(prop in obj) {
    if(!obj.hasOwnProperty(prop)) continue;

    console.log(prop + " - "+ obj[prop]);
}