从Key中检索值的数组

时间:2015-04-13 15:29:26

标签: javascript jquery arrays json algorithm

我正在尝试遍历我拥有的JSON对象,以便检索元素列表。

我正在筛选的JSON代码非常复杂,但这里只是小片段。它基本上显示了我正在寻找的东西。

{
  "ProductsList": [
    {
      "ProductInfo": {
        "Brand": "LG",
        "p_product_barcode": "048231014731",
        "p_product_bullets_json": {
          "Value": [
            "4.3 cubic foot ",
            "Recognized",
            "Customize your washer",
            "6Motion Technology ",
            "Troubleshoot quickly",
            "meow",
            "who",
            "special"
          ]
        }
    }]
}

我正在尝试从“值”获取值列表,该值位于“p_product_bullets_json”内。我想得到所有的元素。

到目前为止,我有这个,但我得到的只是一个空列表。

function getLists(obj, key) {

    // Empty object array
    var objects = [];

    // Searches through the JSON code to find the given key
    for (var k in obj) {

        // If there are still leafs left, then keep searching
        if (!obj.hasOwnProperty(k)) continue;

        // If the leaf doesn't match the key, try again (recursion)
        if (typeof obj[k] == 'object') {

            objects = objects.concat(getValues(obj[k], key));

        // If the leaf does match the key, then push that value onto the array
        } else if (k == key) {

            $.each(obj[k], function(i, val) {

                console.log('Key: ' + i + '  Val: ' + val)

            });
        }
    }

    return objects;
}

我只会浏览每个Key的“Value”,但这个名字并不是唯一的,并且在其他地方还有其他Key具有相同的名称。

非常感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:1)

你需要有一个案例,你从该函数返回一个数组,试试这个:

var input = {
  "ProductsList": [
    {
      "ProductInfo": {
        "Brand": "LG",
        "p_product_barcode": "048231014731",
        "p_product_bullets_json": {
          "Value": [
            "4.3 cubic foot ",
            "Recognized",
            "Customize your washer",
            "6Motion Technology ",
            "Troubleshoot quickly",
            "meow",
            "who",
            "special"
          ]
        }
      }
    }]
};
function getLists(obj, key) {

    var objects = [];

    for (var k in obj) {

        if (!obj.hasOwnProperty(k)) continue;
        if (k == key) {
            if (obj[key] instanceof Array) {
                return obj[key]
            }
        } else if (typeof obj[k] == 'object') {

            objects = objects.concat(getLists(obj[k], key));
        }
    }

    return objects;
}
document.getElementsByTagName('div')[0].innerHTML = JSON.stringify(getLists(input, 'Value'));
    
<div></div>