Need to convert json key-value pairs to standard array

前端 未结 2 1376
自闭症患者
自闭症患者 2020-12-10 09:19

I\'m interperting a json string into a variable using jquery\'s parseJSON() function. The problem is, it\'s turning my data into an object instead of a 2d array. Eg,

相关标签:
2条回答
  • 2020-12-10 10:07

    Once you've deserialized the data (e.g., you have myData, which is an object), you can loop through its keys using for..in, and then build up an array that combines keys and values:

    var myData, dataArray, key;
    myData = $.parse(JSON(data));
    dataArray = [];
    for (key in myData) {
        dataArray.push(key);         // Push the key on the array
        dataArray.push(myData[key]); // Push the key's value on the array
    }
    

    Since myData is the result of deserializing the JSON in data, we know that myData is a generic object (e.g., just a {} as opposed to a new Foo or something like that), so we don't even need hasOwnProperty. If we didn't know that, and we only wanted to enumerate myData's own keys and values, we would add a hasOwnProperty check:

    var myData, dataArray, key;
    myData = $.parse(JSON(data));
    dataArray = [];
    for (key in myData) {
        if (myData.hasOwnProperty(key)) {
            dataArray.push(key);         // Push the key on the array
            dataArray.push(myData[key]); // Push the key's value on the array
        }
    }
    

    There's no reason to do that in your case, unless someone has been mucking about with Object.prototype (in which case, take them behind the woodshed, give them a severe hiding, and then have them write "I will not muck about with Object.prototype several hundred times on the chalkboard), but whenever you use for..in, it's always good to stop and think whether A) The object is guaranteed to be vanilla, and B) If not, do you want only its own properties, or do you also want ones it inherits?

    0 讨论(0)
  • 2020-12-10 10:11
    var data = $.parse(JSON({"feat_3":"4356","feat_4":"45","feat_5":"564","feat_6":"7566"}));
    
    var arr = [];
    
    for( var i in data ) { 
      if( data.hasOwnProperty( i ) ){ 
        arr.push( i,  data[i] );
      }
    }
    

    Array will be :

    ["feat_3", "4356", "feat_4", "45", "feat_5", "564", "feat_6", "7566"]
    
    0 讨论(0)
提交回复
热议问题