从 JSON 数组键值对动态检索键 - Javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7391362/
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
Retrieving Keys from JSON Array key-value pair dynamically - Javascript
提问by Queryer
I have a question that would like to seek your expertise on.
我有一个问题想请教您的专业知识。
This is a JSON array that I have:
这是我拥有的 JSON 数组:
[{"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.
我想要做的是从 JSON 数组而不是值中检索键(A、B、C、D、E)。我能够检索值但不能检索键。
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 keysusing JavaScript?
同样,我应该怎么做才能使用 JavaScript检索密钥?
回答by nrabinowitz
Are you using D3.jsas your tag implies? Because in that case, you can just use d3.keys()
:
您是否如您的标签所暗示的那样使用D3.js?因为在这种情况下,您可以使用d3.keys()
:
var data = [{"A":20,"B":32,"C":27,"D":30,"E":40}];
d3.keys(data[0]); // ["A", "B", "C", "D", "E"]
If you want the sum of all the values, you might be better off using d3.values()
and d3.sum()
:
如果您想要所有值的总和,最好使用d3.values()
and d3.sum()
:
var data = [{"A":20,"B":32,"C":27,"D":30,"E":40}, {"F":50}];
// get total of all object totals
var total = d3.sum(data, function(d) {
// get total of a single object's values
return d3.sum(d3.values(d));
});
total; // 199
回答by Sahil Muthoo
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.
当前发布的所有解决方案都有问题。object.hasOwnProperty(prop)
在使用 for...in 循环迭代对象时,他们都没有检查。如果将属性添加到原型,这可能会导致幻像键出现。
Quoting Douglas Crockford
Be aware that members that are added to the prototype of the object will be included in the enumeration. It is wise to program defensively by using the hasOwnProperty method to distinguish the true members of the object.
请注意,添加到对象原型的成员将包含在枚举中。通过使用 hasOwnProperty 方法来区分对象的真实成员来防御性编程是明智的。
Adding a check for hasOwnProperty
to maerics' excellent solution.
向hasOwnProperty
maerics 的优秀解决方案添加检查。
var getKeys = function (arr) {
var key, keys = [];
for (i = 0; i < arr.length; i++) {
for (key in arr[i]) {
if (arr[i].hasOwnProperty(key)) {
keys.push(key);
}
}
}
return keys;
};
回答by Jord?o
Use for .. in
:
使用for .. in
:
var result = 0;
for (var i = jsonArray.length - 1; i >= 0; --i) {
var o = jsonArray[i];
for (var key in o) {
if (o.hasOwnProperty(key)) {
result += o[key];
}
}
// in your code, you return result here,
// which might not give the right result
// if the array has more than 1 element
}
return result;
回答by Billy Moon
var easy = {
a: 1,
b: 2,
c: 3
}
var keys = [], vals = []
for (var key in easy) {
keys.push(key)
vals.push(easy[key])
}
alert(keys+" - tha's how easy baby, it's gonna be")
alert(vals+" - tha's how easy baby, it's gonna be")
defensively
防御性的
Including @Sahil's defensive method...
包括@Sahil 的防御方法...
for (var key in easy) {
if (easy.hasOwnProperty(key)) {
keys.push(key)
vals.push(easy[key])
}
}
回答by maerics
Try using the JavaScript for..in
statement:
尝试使用JavaScriptfor..in
语句:
var getKeys = function(arr) {
var key, keys = [];
for (i=0; i<arr.length; i++) {
for (key in arr[i]) {
keys.push(key);
}
}
return keys;
};
var a = [{"A":20, "B":32, "C":27, "D":30, "E":40}, {"F":50}]
getKeys(a); // => ["A", "B", "C", "D", "E", "F"]
回答by Do-Gyun Kim
I think this is the simplest.
我认为这是最简单的。
var a = [{"A":20,"B":32,"C":27,"D":30,"E":40}];
Object.keys( a[0] );
Result :
结果 :
["A", "B", "C", "D", "E"]
回答by sangeeth kumar
Try this. It is simple:
尝试这个。很简单:
var a = [{"A":20,"B":32,"C":27,"D":30,"E":40}];
for(var i in a){
for(var j in a[i]){
console.log(j); // shows key
console.log(a[i][j]); // shows value
}
}
回答by user1686644
I think this should be parsed recursively like below
我认为这应该像下面这样递归解析
var getKeys = function(previousKeys,obj){
var currentKeys = Object.keys(obj);
previousKeys = previousKeys.concat(currentKeys);
for(var i=0;i<currentKeys.length;i++){
var innerObj = obj[currentKeys[i]];
if(innerObj!==null && typeof innerObj === 'object' && !Array.isArray(innerObj)){
return this.getKeys(previousKeys,innerObj);
}
}
return previousKeys;
}
usage: getKeys([],{"a":"1",n:{c:"3",e:{ f:4,g:[1,2,3]}}})
用法: getKeys([],{"a":"1",n:{c:"3",e:{ f:4,g:[1,2,3]}}})
Result: ["a", "n", "c", "e", "f", "g"]
结果:["a", "n", "c", "e", "f", "g"]
回答by Tukaram Patil Pune
var _ = require('underscore');
var obj = [{"A":20,"B":32,"C":27,"D":30,"E":40},{"F":50}, {"G":60,"H":70},{"I":80}];
var keys = [], values = [];
_.each(obj, function(d) {
keys.push(_.keys(d));
values.push(_.values(d));
});
// Keys -> [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I' ]
console.log('Keys -> ', _.flatten(keys ));
// Values -> [ 20, 32, 27, 30, 40, 50, 60, 70, 80 ]
console.log('Values -> ', _.flatten(values));