10

任意の数のレベルに移動できるJSON入力があります。

私はの入力サンプルを与えています

var d=getEntities( {"Categories": 
{
"Facets": 
    [
    {
    "count": 1,
    "entity": "Company",
    "Company": 
            [
            {

            "entity": "Ford Motor Co",

            "Ford_Motor_Co": 
                [
                    {
                    "count": 1,
                    "entity": "Ford"
                    }
                ]
            }
            ]
    },
        {
            "count": 4,
            "entity": "Country",
              "Country": [
                    {

                        "entity": "Germany",
                         "Germany": [
                                {
                                    "count": 1,
                                    "entity": "Germany"
                                }
                          ],
                        "currency": "Euro (EUR)"
                    },
                    {

                         "entity": "Italy",
                        "Italy": [
                                {
                                     "count": 1,
                                     "entity": "Italy"
                                }
                          ],
                        "currency": "Euro (EUR)"
                    },
                    {

                        "entity": "Japan",
                          "Japan": [
                             {
                                    "count": 1,
                                    "entity": "Japan"
                             }
                          ],
                        "currency": "Yen (JPY)"
                    },
                    {

                        "entity": "South Korea",
                          "South_Korea": [
                              {
                                    "count": 1,
                                    "entity": "South Korea"
                                }
                          ],
                      "currency": "Won (KRW)"
                    }
              ]
        },
        {"count": 5,
              "entity": "Persons",
              "Persons": [
                    {
                         "count": 2,
                        "entity": "Dodge"
                    },
                    {
                        "count": 1,
                        "entity": "Dodge Avenger"
                    },
                    {
                        "count": 1,
                        "entity": "Major League"
                    },
                    {
                        "count": 1,
                        "entity": "Sterling Heights"
                    }
              ]
        }
  ]

}});

再帰を使用して、すべてのレベルのキー値「エンティティ」を配列に追加したいのですが、

文字列を使用して第1レベルからデータを収集できます

<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript" src="dataDumper.js"></script>


<script type="text/javascript">

var testJSON = {"Categories": 
{
"Facets": 
    [
    {
    "count": 1,
    "entity": "Company",
    "Company": 
            [
            {

            "entity": "Ford Motor Co",

            "Ford_Motor_Co": 
                [
                    {
                    "count": 1,
                    "entity": "Ford"
                    }
                ]
            }
            ]
    },
        {
            "count": 4,
            "entity": "Country",
              "Country": [
                    {

                        "entity": "Germany",
                         "Germany": [
                                {
                                    "count": 1,
                                    "entity": "Germany"
                                }
                          ],
                        "currency": "Euro (EUR)"
                    },
                    {

                         "entity": "Italy",
                        "Italy": [
                                {
                                     "count": 1,
                                     "entity": "Italy"
                                }
                          ],
                        "currency": "Euro (EUR)"
                    },
                    {

                        "entity": "Japan",
                          "Japan": [
                             {
                                    "count": 1,
                                    "entity": "Japan"
                             }
                          ],
                        "currency": "Yen (JPY)"
                    },
                    {

                        "entity": "South Korea",
                          "South_Korea": [
                              {
                                    "count": 1,
                                    "entity": "South Korea"
                                }
                          ],
                      "currency": "Won (KRW)"
                    }
              ]
        },
        {"count": 5,
              "entity": "Persons",
              "Persons": [
                    {
                         "count": 2,
                        "entity": "Dodge"
                    },
                    {
                        "count": 1,
                        "entity": "Dodge Avenger"
                    },
                    {
                        "count": 1,
                        "entity": "Major League"
                    },
                    {
                        "count": 1,
                        "entity": "Sterling Heights"
                    }
              ]
        }
  ]

}};

function scan(obj)
{
    var k;
    if (obj.hasOwnProperty('entity')) {



        for (k in obj){
           if (obj.hasOwnProperty(k)){


                scan( obj[k] );  


            }                
          }
    } 


    else{
        if(k=='entity')
        {
        alert(obj.entity);
   }
    }


};

scan(testJSON);



</script>
</head>

<body>

</body>

</html>

再帰関数を使用してJSON文字列の内部レベルに入るにはどうすればよいですか?

4

5 に答える 5

22

私は、JSオブジェクト内のすべてのオブジェクト、配列、および値を次のようにトラバースするjsfiddleを作成しました...

function scan(obj) {
    var k;
    if (obj instanceof Object) {
        for (k in obj){
            if (obj.hasOwnProperty(k)){
                //recursive call to scan property
                scan( obj[k] );  
            }                
        }
    } else {
        //obj is not an instance of Object so obj here is a value
    };

};

(Chromeで)再帰エラーは発生しません。これを使ってやりたいことができますか?

オブジェクトが配列であるかどうかをテストする必要がある場合は、if (obj instanceof Array)

オブジェクトに「エンティティ」プロパティがあるかどうかをテストするには、if (obj.hasOwnProperty('entity'))

「エンティティ」プロパティを追加(または既存)するには、obj.entity = valueまたはobj['entity'] = value

于 2012-05-05T08:18:56.687 に答える
1
(function recur( obj ) {
    Object.keys( obj ).forEach( function( prop ) {
        // Check if the property is an object
        if ( ({}).toString.apply( prop ) === '[object Object]' ) {
            // If it is, recall this function
            recur( prop );
        }
    } );
} () );

ロジックは追加していませんが、オブジェクトを再帰的にトラバースする方法がわかります。

于 2012-05-05T07:49:45.537 に答える
1

私が次のような構造を持っているとしましょう:

var aObject = {
    items: [],
    children: {}
}

子は、より多くのaObjectを含む連想配列です。したがって、次のようになります。

var aObject = {
    items: [],
    children: {
        "subgroup1": {
            items: [],
            children: {}
        },
        "subgroup2": {
            items: [],
            children: {}
        }
    }
}

サブグループの配列を含むアイテムがあります。

["subgroup1", "subgroup1a"]

各サブグループは「場所」です。アイテムは次の場所に配置する必要があります。

aObject.children[array[0]].children[array[1]].items

各レベルで、children [array [i]]が存在するかどうかを確認し、存在しない場合は作成する必要があります。children [array [0]]がまだ存在していない可能性があり、エラーが発生するため、aObject.children[array[0]]。children[array[1]]。items.push(item)と単純に記述することはできません。

これは再帰を使用して解決できます!(AngularJS)

function recursive(aLevel, aItem, aArray, aIndex){
    var lLevel = aLevel;

    // If we have reached the end of the array
    if (aIndex === aArray.length){
        // Insert
        aLevel.items.push(aItem);
    } else {

        // If the subgroup doesn't exist, create it
        if (typeof aLevel.children[aArray[aIndex]] === 'undefined'){
            aLevel.children[aArray[aIndex]] = {
              items: [],
              children: {}
            };
        }

        // Move into
        recursive(aLevel.children[aArray[aIndex]], aItem, aArray, aIndex+1);
    }
}

aObject = {
    items: [],
    children: {},
}

angular.forEach(items, function(item, i){
    var location = item.location;

    if (location.length == 0){
        aObject.items.push(item);
    } else {
        recursive(aObject, item, location, 0);
    }
});

最終的なaObjectは次のようになります。

var aObject = {
     items: [],
     children: {
        "subgroup1": {
            items: [],
            children: {
                "subgroup1a": {
                    items: [item],
                    children: {}
                }
            }
        },
        "subgroup2": {
            items: [],
            children: {}
        }
    }
}
于 2016-04-19T01:26:21.720 に答える
1

これが私がよく使う関数です。多くの再帰的なタスクを実行するために簡単に変更できます。たとえば、ベイルフラグを追加すると、スタックをすばやく取得したり、さらに一般的なコールバック関数を追加したりできます。とにかくそれは私の2セントです

var recursiveObjMap = (function(){
  var stack = [];
  var result = [];
  // var bail = false;
  return function map(data, key){
    if (!$.isArray(data) && !$.isPlainObject(data) ) { 
      result.push(data);
      return false 
    }

    $.each(data, function(i, v){
      if (key) stack.push(key);
      map(v, i);
      stack.pop();
    });
    return result;
  };
})();

recursiveObjMap({a:'b',c:{d:{e:"f"}}}) // ['b', 'f']
于 2016-10-06T06:41:35.363 に答える
0
const obj = [
  {
    count: 1,
    entity: "Company",
    Company: [
      {
        entity: "Ford Motor Co",

        Ford_Motor_Co: [
          {
            count: 1,
            entity: "Ford",
          },
        ],
      },
    ],
  },
  {
    count: 4,
    entity: "Country",
    Country: [
      {
        entity: "Germany",
        Germany: [
          {
            count: 1,
            entity: "Germany",
          },
        ],
        currency: "Euro (EUR)",
      },
      {
        entity: "Italy",
        Italy: [
          {
            count: 1,
            entity: "Italy",
          },
        ],
        currency: "Euro (EUR)",
      },
      {
        entity: "Japan",
        Japan: [
          {
            count: 1,
            entity: "Japan",
          },
        ],
        currency: "Yen (JPY)",
      },
      {
        entity: "South Korea",
        South_Korea: [
          {
            count: 1,
            entity: "South Korea",
          },
        ],
        currency: "Won (KRW)",
      },
    ],
  },
  {
    count: 5,
    entity: "Persons",
    Persons: [
      {
        count: 2,
        entity: "Dodge",
      },
      {
        count: 1,
        entity: "Dodge Avenger",
      },
      {
        count: 1,
        entity: "Major League",
      },
      {
        count: 1,
        entity: "Sterling Heights",
      },
    ],
  },
];
function test(runObj) {
  for (let i in runObj) {
    typeof runObj[i] == "object" ? test(runObj[i]) : console.log(runObj[i]);
  }
}
test(obj);
于 2020-10-30T00:34:19.743 に答える