遍历表行只选择特定的列名和值

时间:2014-04-11 10:58:05

标签: javascript json

我是初学者,并且不知道如何从JSON获取数据。我有以下JSON结构,

{
"title": "Delicate style of embroidery lawn dress",
"field": [
    {
        "row1": {
            "key": "free_homedelivery",
            "value": "yes"
        }
    },
    {
        "row2": {
            "key": "_price",
            "value": "60"
        }
    },
    {
        "row3": {
            "key": "_regular_price",
            "value": "60"
        }
    },
    {
        "row4": {
            "key": "_stock_status",
            "value": "instock"
        }
    }
         ]
}

我试过了,但控制台说undefined

for(var i =0 ;i < s.length; i++)
{
console.log('key ' + s.field['row'+i].key);
}

这似乎没有获取值......

Here is the Fiddle

2 个答案:

答案 0 :(得分:1)

问题

  1. 什么是s? - 假设s是您粘贴的json
  2. 迭代在s.field上,但s.length已使用
  3. field称为数组,但尝试访问数组内对象的属性作为数组的属性。
  4. 数组迭代从0开始,row名称以row1
  5. 开头

    var numFields = s.field.length; // Good practice to keep length calculated
    for(var i = 0; i < numFields; i++){
        console.log('key ' + s.field[i]['row'+(i+1)].key);
    }
    

    脚注 - JSON太复杂了,它可以像下面这样简单,

    var s = {
        "title": "Delicate style of embroidery lawn dress",
        "field": [
            {
                "key": "free_homedelivery",
                "value": "yes"
            },
            {
                "key": "_price",
                "value": "60"
            }
        ]
    };
    // Updated loop
    var numFields = s.field.length; // Good practice to keep length calculated
    for(var i = 0; i < numFields; i++){
        console.log('key ' + s.field[i].key);
    }
    

    希望这有帮助!

    小提琴 - http://jsfiddle.net/n4J5U/

答案 1 :(得分:0)

你在json中的对象有点不同(属性名称是row1,row2等),所以你必须做这样的事情:

var json = {
    "title": "Delicate style of embroidery lawn dress",
        "field": [{
        "row1": {
            "key": "free_homedelivery",
                "value": "yes"
        }
    }, {
        "row2": {
            "key": "_price",
                "value": "60"
        }
    }, {
        "row3": {
            "key": "_regular_price",
                "value": "60"
        }
    }, {
        "row4": {
            "key": "_stock_status",
                "value": "instock"
        }
    }]
}

for (i = 0; i < json.field.length ; i++){
    var item = json.field[i];    
    var key = item["row" + (i + 1)].key;
    alert(key);
}
  

Fiddle