遍历嵌套的 json 对象数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15268594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:47:12  来源:igfitidea点击:

Iterate through nested json object array

javascriptjson

提问by Saurabh

I have to iterate through json array object.

我必须遍历 json 数组对象。

It has following structure.

它具有以下结构。

var myJSONObject = {
    "abc": {
        "prod_1": [
            {"prod_ver" : "prod 1 ver 1"},
            {"prod_ver" : "prod 1 ver 2"},
        ],
        "prod_2": [
            {"prod_ver" : "prod 2 ver 1"},
            {"prod_ver" : "prod 2 ver 2"},
        ],
        "prod_3": [
            {"prod_ver" : "prod 3 ver 1"},
            {"prod_ver" : "prod 3 ver 2"},
        ]
    }
};

Basically what I am doing is prod_1 is name of a product and the list of versions that prod_1 has are populated inside it.

基本上我正在做的是 prod_1 是产品的名称,并且 prod_1 具有的版本列表填充在其中。

So now what i want is the name of the product as well as what versions it has.

所以现在我想要的是产品的名称以及它的版本。

The problem is there can be many products and many versions under that product. So i need a proper looping structure in javascriptthat can be generic to handle it.

问题是该产品下可以有许多产品和许多版本。所以我需要一个适当的javascript循环结构,它可以是通用的来处理它。

It would be best if the loop stores product name in one var and it's version in another var as there are some checking i need to on product name.

如果循环将产品名称存储在一个 var 中并将其版本存储在另一个 var 中,那将是最好的,因为我需要对产品名称进行一些检查。

If the json structure is wrong or a better json structure can be written the please suggest a right/better structure.

如果 json 结构错误或可以编写更好的 json 结构,请提出正确/更好的结构。

Please HELP

帮助

Thanks in advance.

提前致谢。

回答by Korijn

Since myJSONObject.abccontains a list of products it would make more sense to define the property abcas an array. Like this:

由于myJSONObject.abc包含产品列表,将属性定义abc为数组会更有意义。像这样:

var myJSONObject = 
{
"abc":
    [
        [
            {"prod_ver" : "prod 1 ver 1"},
            {"prod_ver" : "prod 1 ver 2"},
        ],
        [
            {"prod_ver" : "prod 2 ver 1"},
            {"prod_ver" : "prod 2 ver 2"},
        ],
        [
            {"prod_ver" : "prod 3 ver 1"},
            {"prod_ver" : "prod 3 ver 2"},
        ]
    ]
};

Then you can iterate over the products and their versions using normal loops:

然后您可以使用普通循环迭代产品及其版本:

for(var i = 0; i < myJSONObject.abc.length; i++)
{
    var product = myJSONObject.abc[i];
    for(var j = 0; j < product.length; j++)
    {
        var version = product[j];
    }
}

You could take it slightly further and alter your JSON object's structure a bit to make it more easily understandable.

您可以更进一步,稍微改变一下 JSON 对象的结构,使其更易于理解。

var catalog = 
{
    "products": [
        {
            "name": "prod 1",
            "versions": [
                "ver 1",
                "ver 2"
            ]
        },
        {
            "name": "prod 2",
            "versions": [
                "ver 1",
                "ver 2"
            ]
        }
    ]
};

for(var i = 0; i < catalog.products.length; i++)
{
    var product = catalog.products[i];
    var productName = product.name;
    for(var j = 0; j < product.versions.length; j++)
    {
        var version = product.versions[j];
    }
}

回答by T.J. Crowder

myJSONObject.abcis an object with keys like prod_1, prod_2, etc. You can loop through the keys of an object using for-in. So:

myJSONObject.abc是一个带有诸如prod_1prod_2等键的对象for-in。您可以使用 遍历对象的键。所以:

var productName;
var productVersionArray;

for (productName in myJSONObject.abc) {
    productVersionArray = myJSONObject.abc[productName];
}

Note that the order of the keys is not defined by the specification and will vary from JavaScript engine to JavaScript engine. If you want to do them in a particular order, you have to get an array of them, sort it in the order you want, and then loop through that array. (In an ES5-enabled environment, you can get an array of the keys of an object from Object.keys(yourObject). But you'd need a shim for older browsers.)

请注意,规范中未定义键的顺序,并且会因 JavaScript 引擎而异。如果您想按特定顺序执行它们,则必须获取它们的数组,按所需顺序对其进行排序,然后循环遍历该数组。(在启用 ES5 的环境中,您可以从 中获取对象键的数组Object.keys(yourObject)。但是对于旧浏览器,您需要一个垫片。)

Within that loop, you can loop through the array using a standard forloop:

在该循环中,您可以使用标准for循环遍历数组:

for (versionIndex = 0; versionIndex < productVersionArray.length; ++versionIndex) {
    // Use `productVersionArray[versionIndex].prod_ver` here
}

Here's an example putting it all together:

这是一个将所有内容放在一起的示例:

(function() {

  var myJSONObject = 
    {
    "abc":
        {
            "prod_1": 
            [
                {"prod_ver" : "prod 1 ver 1"},
                {"prod_ver" : "prod 1 ver 2"}
            ],

            "prod_2": 
            [
                {"prod_ver" : "prod 2 ver 1"},
                {"prod_ver" : "prod 2 ver 2"}
            ],
            "prod_3": 
            [
                {"prod_ver" : "prod 3 ver 1"},
                {"prod_ver" : "prod 3 ver 2"}
            ]
        }
    };

  var productName;
  var productVersionArray;
  var versionIndex;

  for (productName in myJSONObject.abc) {
      productVersionArray = myJSONObject.abc[productName];
      display(productName + " has " + productVersionArray.length + " versions listed");
      for (versionIndex = 0; versionIndex < productVersionArray.length; ++versionIndex) {
        display("* " + productVersionArray[versionIndex].prod_ver);
      }
  }

  function display(msg) {
    var p = document.createElement('p');
    p.innerHTML = String(msg);
    document.body.appendChild(p);
  }

})();

Live Copy| Source

实时复制| 来源

回答by Vishwanath

function z() {
  for (let key in myJSONObject.abc) {
    let value = myJSONObject.abc[key];
    for (let i = 0; i <= value.length; i++) {
      console.log(value[[i]]);
    }
  }
}

回答by Lae Kettavong

Updated with ES6

用 ES6 更新

  var { products } =
    {
        "products": [
            {
                "name": "prod 1",
                "versions": [
                    "ver 1",
                    "ver 2"
                ]
            },
            {
                "name": "prod 2",
                "versions": [
                    "ver 1",
                    "ver 2"
                ]
            },
            {
                "name": "prod 3",
                "versions": [
                    "ver 1",
                    "ver 2"
                ]
            }
        ]
    };

    let inventory = products.reduce((accumulator, currentValue) => {
        let { name, versions } = currentValue;
        accumulator[name] = versions
        return accumulator
    }, []);

    Object.entries(inventory).forEach((prod) => {
        let prodName = prod[0];
        let prodVers = prod[1].join(", ");
    });