动态从 JSON 数组键值对检索键 - Javascript

发布于 2024-12-04 16:53:10 字数 588 浏览 0 评论 0原文

我有一个问题想寻求您的专业知识。

这是我拥有的一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

把昨日还给我 2024-12-11 16:53:10

您是否像标签所暗示的那样使用 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"] 

如果您想要所有值的总和,您最好使用 d3.values() 和 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

Are you using D3.js as your tag implies? Because in that case, you can just use 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():

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
帅冕 2024-12-11 16:53:10

当前发布的所有解决方案都有问题。它们都没有检查 object.hasOwnProperty(prop)使用 for...in 循环迭代对象时。如果将属性添加到原型,这可能会导致出现幻像键。

引用道格拉斯·克罗克福德

请注意,添加到对象原型的成员将包含在枚举中。通过使用 hasOwnProperty 方法来区分对象的真正成员,进行防御性编程是明智的。

在 maerics 的优秀解决方案中添加了对 hasOwnProperty 的检查。

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;
    };

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

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.

Adding a check for hasOwnProperty to maerics' excellent solution.

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;
    };
嗼ふ静 2024-12-11 16:53:10

使用 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;

Use 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;
为你拒绝所有暧昧 2024-12-11 16:53:10
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")

防御性

包括@Sahil的防御方法......

for (var key in easy) {
    if (easy.hasOwnProperty(key)) {
        keys.push(key)
        vals.push(easy[key])
    }
}
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...

for (var key in easy) {
    if (easy.hasOwnProperty(key)) {
        keys.push(key)
        vals.push(easy[key])
    }
}
旧夏天 2024-12-11 16:53:10

尝试使用 JavaScript for..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"]

Try using the JavaScript for..in statement:

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"]
怪我鬧 2024-12-11 16:53:10

我认为这是最简单的。

var a = [{"A":20,"B":32,"C":27,"D":30,"E":40}];
Object.keys( a[0] );

结果 :

["A", "B", "C", "D", "E"]

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"]
半仙 2024-12-11 16:53:10

for-in 循环就可以解决这个问题。在一个对象上它看起来像这样:

var o = {
    a: 5,
    b: 3
};
var num = 0;

for (var key in o) {
    num += o[key];
}
alert(num);

A for-in-loop does the trick. On one object it looks like this:

var o = {
    a: 5,
    b: 3
};
var num = 0;

for (var key in o) {
    num += o[key];
}
alert(num);
蓝天 2024-12-11 16:53:10

试试这个。很简单:

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
  }
}

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
  }
}
凡尘雨 2024-12-11 16:53:10

我认为这应该像下面的用法一样递归解析

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;
    }

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

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]}}})

Result:
["a", "n", "c", "e", "f", "g"]

誰認得朕 2024-12-11 16:53:10
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));
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));
裸钻 2024-12-11 16:53:10

停止重新发明轮子

Object.keys()

MDN

stop reinventing the wheel !

Object.keys()

MDN

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文