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
JSON forEach get Key and Value
提问by gespinha
I have the following forEach
loop over a JSON object called obj
:
我在forEach
名为 的 JSON 对象上有以下循环obj
:
Object.keys(obj).forEach(function(){
});
How can I make it console.log
both key
and value
of each item inside the object? Something like this:
我怎样才能使console.log
双方key
和value
对象内部的每一个项目的?像这样的东西:
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
回答by duncanhall
Assuming that obj
is 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]);
}