Change key name in nested JSON structure

前端 未结 3 1580
名媛妹妹
名媛妹妹 2020-12-10 18:53

I have a JSON data structure as shown below:

{
    \"name\": \"World\",
    \"children\": [
      { \"name\": \"US\",
          \"children\": [
           {          


        
3条回答
  •  春和景丽
    2020-12-10 19:27

    Try this:

    function convert(data){
      return {
        key: data.name,
        value: data.children.map(convert);
      };
    }
    

    Or if you need to support older browsers without map:

    function convert(data){
      var children = [];
      for (var i = 0, len = data.children.length; i < len; i++){
        children.push(convert(data.children[i]));
      }
    
      return {
        key: data.name,
        value: children
      };
    }
    

提交回复
热议问题