Separate key and value pairs into two arrays

后端 未结 4 1430
忘了有多久
忘了有多久 2021-01-13 22:48

What would be the best way to go about separating the key and values into two different arrays so that this -

var data = {\"A Key\": 34, \"Another Key\": 16         


        
4条回答
  •  独厮守ぢ
    2021-01-13 23:25

    You can loop through the properties with a for in loop, and then just assign them to arrays as needed.

    Make sure you check whether the key is a property of the object, and not of the prototype.

    var data1 = [];
    var data2 = [];
    
    for (var key in p) {
      if (p.hasOwnProperty(key)) {
        data1.push(key);
        data2.push(p[key]);
      }
    }
    

提交回复
热议问题