Change key name in nested JSON structure

前端 未结 3 1504
名媛妹妹
名媛妹妹 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
      };
    }
    
    0 讨论(0)
  • 2020-12-10 19:33

    I don't know why you have a semicolon at the end of your JSON markup (assuming that's what you've represented in the question), but if that's removed, then you can use a reviver function to make modifications while parsing the data.

    var parsed = JSON.parse(myJSONData, function(k, v) {
        if (k === "name") 
            this.key = v;
        else if (k === "children")
            this.value = v;
        else
            return v;
    });
    

    DEMO: http://jsfiddle.net/BeSad/

    0 讨论(0)
  • 2020-12-10 19:49

    You could use a function like this :

    function clonerename(source) {
        if (Object.prototype.toString.call(source) === '[object Array]') {
            var clone = [];
            for (var i=0; i<source.length; i++) {
                clone[i] = goclone(source[i]);
            }
            return clone;
        } else if (typeof(source)=="object") {
            var clone = {};
            for (var prop in source) {
                if (source.hasOwnProperty(prop)) {
                    var newPropName = prop;
                    if (prop=='name') newPropName='key';
                    else if (prop=='children') newPropName='value';
                    clone[newPropName] = clonerename(source[prop]);
                }
            }
            return clone;
        } else {
            return source;
        }
    }
    
    var B = clonerename(A);
    

    Note that what you have isn't a JSON data structure (this doesn't exist as JSON is a data-exchange format) but probably an object you got from a JSON string.

    0 讨论(0)
提交回复
热议问题