动态从 JSON 数组键值对检索键 - Javascript
我有一个问题想寻求您的专业知识。
这是我拥有的一个 JSON 数组:
[{"A":20,"B":32,"C":27,"D":30,"E":40}]
我想做的是从 JSON 数组中检索键(A、B、C、D、E)而不是值。我能够检索值,但不能检索键。
我使用它来动态检索值:
function calculateSum(jsonArray) {
var result = 0;
for (var i = jsonArray.length - 1; i >= 0; --i)
{
var o = jsonArray[i];
A = o.A;
B = o.B;
C = o.C;
D = o.D;
E = o.E;
result = A + B + C + D + E;
return result;
}
return result;
}
同样,我应该如何使用 JavaScript 检索键?
I have a question that would like to seek your expertise on.
This is a JSON array that I have:
[{"A":20,"B":32,"C":27,"D":30,"E":40}]
What I would like to do is to retrieve the keys (A, B, C, D, E) from the JSON array instead of the values. I am able to retrieve the values but not the keys.
I am using this to retrieve the values dynamically:
function calculateSum(jsonArray) {
var result = 0;
for (var i = jsonArray.length - 1; i >= 0; --i)
{
var o = jsonArray[i];
A = o.A;
B = o.B;
C = o.C;
D = o.D;
E = o.E;
result = A + B + C + D + E;
return result;
}
return result;
}
Similarly, what should I do to retrieve the keys using JavaScript?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
您是否像标签所暗示的那样使用 D3.js ?因为在这种情况下,您可以只使用 d3.keys() :
如果您想要所有值的总和,您最好使用 d3.values() 和 d3.sum():
Are you using D3.js as your tag implies? Because in that case, you can just use
d3.keys()
:If you want the sum of all the values, you might be better off using
d3.values()
andd3.sum()
:当前发布的所有解决方案都有问题。它们都没有检查
object.hasOwnProperty(prop)
使用 for...in 循环迭代对象时。如果将属性添加到原型,这可能会导致出现幻像键。引用道格拉斯·克罗克福德
在 maerics 的优秀解决方案中添加了对
hasOwnProperty
的检查。All of the current posted solutions have a problem. None of them check for
object.hasOwnProperty(prop)
while iterating over an object using a for...in loop. This might cause phantom keys to appear if properties are added to the prototype.Quoting Douglas Crockford
Adding a check for
hasOwnProperty
to maerics' excellent solution.使用
for ..in
:Use
for .. in
:防御性
包括@Sahil的防御方法......
defensively
Including @Sahil's defensive method...
尝试使用 JavaScript
for..in
声明:Try using the JavaScript
for..in
statement:我认为这是最简单的。
结果 :
I think this is the simplest.
Result :
for-in
循环就可以解决这个问题。在一个对象上它看起来像这样:A
for-in
-loop does the trick. On one object it looks like this:试试这个。很简单:
Try this. It is simple:
我认为这应该像下面的用法一样递归解析
:
getKeys([],{"a":"1",n:{c:"3",e:{ f:4,g:[1,2 ,3]}}})
结果:
[“a”、“n”、“c”、“e”、“f”、“g”]
I think this should be parsed recursively like below
usage:
getKeys([],{"a":"1",n:{c:"3",e:{ f:4,g:[1,2,3]}}})
Result:
["a", "n", "c", "e", "f", "g"]
停止重新发明轮子!
MDN
stop reinventing the wheel !
MDN