简体   繁体   English

使用键0/1(而不是键名称)访问JSON

[英]Access JSON using key 0 / 1 instead of name of key

I have json that looks more or less like this: 我有或多或少看起来像这样的json:

{
    "TaskCategoryType": [
        {
            "PK_Column_Value": "C",
            "Column_Description": "Consumables"
        },
        //...
    }

I need to retrieve the value of "PK_Column_Value" without knowing the name of the key. 我需要在不知道键名的情况下检索“ PK_Column_Value”的值。

Looping through and getting the record is fine, but I don't want: 遍历并获取记录很好,但是我不想要:

row.PK_Column_Value

in my Javascript as, at runtime, I do not know the name "PK_Column_Value", only that it's the first in the 2 column "pair" per json row. 在我的Javascript中,在运行时,我不知道名称“ PK_Column_Value”,只是它是每个json行的2列“ pair”中的第一个。

I tried: row[0] but it gives back undefined. 我试过了:row [0]但它返回未定义的。

I want to load a select dropdown box with the value of "PK_Column_Value" and the text of "Description", but I want to send through other json data that has a different column name for the value in JSON. 我想使用“ PK_Column_Value”的值和“ Description”的文本加载一个选择下拉框,但是我想通过JSON值中具有不同列名的其他JSON数据进行发送。

The best you can do is loop and check, different browsers can produce different order of objects: 最好的办法是循环检查,不同的浏览器可以产生不同顺序的对象:

for (var i = 0; i < data.TaskCategoryType.length; i++) {
    for (var key in data.TaskCategoryType[i]) {
        console.log(data.TaskCategoryType[i][key]) //Your keys
    }
}

The only "clean" way would be to restructure your JSON to contain arrays instead of objects. 唯一“干净”的方法是将JSON重组为包含数组而不是对象。

{
"TaskCategoryType": [
    [
        "C",
        "Consumables"
    ],
    //...
}

But personally I'd keep it that way, it makes the code much easier to read and maintain. 但就我个人而言,我会保持这种方式,这样会使代码更易于阅读和维护。

Assuming your object only has two keys and you know the other key; 假设您的对象只有两个键,而您知道另一个键。

var o = {
    "PK_Column_Value": "C",
    "Column_Description": "Consumables"
};
  1. get the keys 得到钥匙

     var keys = [], k; for (k in o) keys.push(k); 
  2. find Column_Description 找到Column_Description

     i = keys.indexOf('Column_Description'); 
  3. get the other key 得到另一个钥匙

     k = keys[1 - i]; 

Now 现在

k === 'PK_Column_Value';

This solves the fact you can't guarantee key order 这解决了您不能保证关键订单的事实

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

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