简体   繁体   English

如何使用Jquery或JS获取数组的对象名

[英]How to get the objectname of array with Jquery or JS

I guess this is relativly easy, but I just can't figure out how to do this. 我想这相对容易,但是我不知道该怎么做。

part of the HTML/JS (Jquery) file HTML / JS(Jquery)文件的一部分

  var checkedBox = $('input[name=ProductType]:checked').val();

            $.getJSON('getdata.php', {ProductType: checkedBox}, function(getit) {
                $.each(getit, function(index, array) {

After fetching a variable array thru JSON from a PHP file. 从PHP文件通过JSON获取变量数组之后。 I can see the following information in the console: 我可以在控制台中看到以下信息:

Console 安慰

[{"color":"red"},{"color":"blue"},{"color":"yellow"}]

Depending on the value of the checkbox, the PHP file will return the array objectname. 根据复选框的值,PHP文件将返回数组对象名。 (In this case "color") with its corresponding values. (在这种情况下为“颜色”)及其相应的值。

Now I would like to catch this array objectname in a var with Jquery or JS, because the array objectnames can differ. 现在,我想用Jquery或JS在var中捕获此数组对象名,因为数组对象名可以不同。 But how can I do this? 但是我该怎么办呢?

I'm guessing that what you want to do is to extract the name from the JSON data. 我猜您想做的是从JSON数据中提取名称。 If you have this data that comes back from your PHP JSON: 如果您有从PHP JSON返回的数据:

var getit = [{"color":"red"},{"color":"blue"},{"color":"yellow"}];

And, you want to get the common attribute name from that and all values in the array have the same name, you could so so like this: 并且,您想从中获取通用属性名称,并且数组中的所有值都具有相同的名称,您可以这样:

function getKeyName(data) {
    var firstItem = data[0];  // look at first array element
    for (var i in firstItem) {
        return(i);  // return first property name found
    }
}

var attributeName = getKeyName(getit);

If you control the JSON data format, I would think it would be a more useful data format to have it like this: 如果您控制JSON数据格式,那么我认为使用这种格式将是一种更有用的数据格式:

{"name": "color", "values": ["red", "blue", "yellow"]}

Then you could directly access: 然后,您可以直接访问:

data.name   // "color"
data.values // ["red", "blue", "yellow"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM