简体   繁体   中英

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

  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. 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. (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. But how can I do this?

I'm guessing that what you want to do is to extract the name from the JSON data. If you have this data that comes back from your 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:

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

Then you could directly access:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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