node.js 从 NodeJS 中的 JSON 列表中获取键值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35837338/
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
Get key value from the list of JSON in NodeJS
提问by user1662039
I am receiving the JSON object as a list of objects:
我正在接收 JSON 对象作为对象列表:
result=[{"key1":"value1","key2":"value2"}]
I am trying to retrieve the values from this list in Node.js. I used JSON.stringify(result)but failed. I have been trying to iterate the list using for(var key in result)with no luck, as it prints each item as a key.
我正在尝试从 Node.js 中的此列表中检索值。我用过JSON.stringify(result)但是失败了。我一直在尝试使用for(var key in result)没有运气的迭代列表,因为它将每个项目打印为一个键。
Is anyone facing a similar issue or has been through this? Please point me in the right direction.
有没有人遇到过类似的问题或经历过这个问题?请指出我正确的方向。
回答by Florent B.
If your result is a string then:
如果您的结果是字符串,则:
var obj = JSON.parse(result);
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
console.log(obj[keys[i]]);
}
回答by Chitharanjan Das
Okay, assuming that resulthere is a string, the first thing you need to do is to convert (deserialize) it to a JavaScript object. A great way of doing this would be:
好的,假设result这里是一个字符串,您需要做的第一件事就是将它转换(反序列化)为一个 JavaScript 对象。这样做的一个好方法是:
array = JSON.parse(result)
Next you loop through each item in the array, and for each item, you can loop through the keys like so:
接下来循环遍历数组中的每一项,对于每一项,你可以循环遍历键,如下所示:
for(var idx in array) {
var item = array[idx];
for(var key in item) {
var value = item[key];
}
}
回答by vinayakj
Lookslike you are pointing to wrong object. Either do like
看起来您指向了错误的对象。要么喜欢
var result = [{"key1":"value1","key2":"value2"}];
for(var key in result[0]){ alert(key);}
or
或者
var keys = Object.keys([{"key1":"value1","key2":"value2"}][0]);
alert(keys);
回答by Shiva
try this code:
试试这个代码:
For result=[{"key1":"value1","key2":"value2"}]
Below will print the values for Individual Keys:
下面将打印单个键的值:
console.log(result[0].key1)
console.log(result[0].key2)
回答by Avalanchd
Wouldn't this just be:
这不就是:
let obj = JSON.parse(result);
let arrValues = Object.values(obj);
which would give you an array of just the values to iterate over.
这将为您提供一个仅包含要迭代的值的数组。
回答by pride
A little different approach:
有点不同的方法:
let result=[{"key1":"value1","key2":"value2"}]
for(let i of result){
console.log("i is: ",i)
console.log("key is: ",Object.keys(i));
console.log("value is: ",Object.keys(i).map(key => i[key])) // Object.values can be used as well in newer versions.
}

