猿问

遍历嵌套的JavaScript对象

我试图遍历嵌套对象以检索由字符串标识的特定对象。在下面的示例对象中,标识符字符串是“ label”属性。我无法解决如何遍历树以返回适当对象的问题。任何帮助或建议,将不胜感激。


var cars = {

  label: 'Autos',

  subs: [

    {

      label: 'SUVs',

      subs: []

    },

    {

      label: 'Trucks',

      subs: [

        {

          label: '2 Wheel Drive',

          subs: []

        },

        {

          label: '4 Wheel Drive',

          subs: [

            {

              label: 'Ford',

              subs: []

            },

            {

              label: 'Chevrolet',

              subs: []

            }

          ]

        }

      ]

    },

    {

      label: 'Sedan',

      subs: []

    }

  ]

}


斯蒂芬大帝
浏览 1588回答 3
3回答

长风秋雁

您可以创建像这样的递归函数来对cars对象进行深度优先遍历。var findObjectByLabel = function(obj, label) {    if(obj.label === label) { return obj; }    for(var i in obj) {        if(obj.hasOwnProperty(i)){            var foundLabel = findObjectByLabel(obj[i], label);            if(foundLabel) { return foundLabel; }        }    }    return null;};可以这样称呼findObjectByLabel(car, "Chevrolet");

慕雪6442864

如果你想深遍历到一个复杂的(嵌套)对象为每个键和值,你可以这样做使用Object.keys() ,递归:const iterate = (obj) => {    Object.keys(obj).forEach(key => {    console.log(`key: ${key}, value: ${obj[key]}`)    if (typeof obj[key] === 'object') {            iterate(obj[key])        }    })}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答