how to convert nested object into array of array

为君一笑 提交于 2021-01-28 09:52:15

问题


Hi i have a situation where i want to convert array of object into array of array

here is my targeted array of objects which looks like this

(32) [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]0: Object1: Object2: Object3: Object4: Object5: Object6: Object7: Object8: Object9: Object10: Object11: Object12: Object13: Object14: Object15: Object16: Object17: Object18: Object19: Object20: Object21: Object22: Object23: Object24: Object25: Object26: Object27: Object28: Object29: Object30: Object31: Objectlength: 32__proto__: Array(0)

i think it has the structure like this :

targetObject = [

{location: "MUGABALA  KOLAR ROAD", latitude: 13.108435679884, longitude: 77.890262391016},

{location: "pune", latitude: 18.6202008, longitude: 73.7908073},

{location: "RAJARAJESHWARI NAGAR BANGLORE", latitude: 12.901112992767, longitude: 77.5037757}

];

My desired Output:

    $resultant = [
             ["MUGABALA  KOLAR ROAD", 13.108435679884, 77.890262391016],

              ["pune",  18.6202008, 73.7908073],

            ["RAJARAJESHWARI NAGAR BANGLORE", 12.901112992767, 77.5037757]

];

回答1:


You could map the result of Object.values.

For older user agents, you could use a polyfill.

var array = [{ location: "MUGABALA  KOLAR ROAD", latitude: 13.108435679884, longitude: 77.890262391016 }, { location: "pune", latitude: 18.6202008, longitude: 73.7908073 }, { location: "RAJARAJESHWARI NAGAR BANGLORE", latitude: 12.901112992767, longitude: 77.5037757 }],
    result = array.map(Object.values);
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }



回答2:


You can do it using Object.values() and Array.prototype.map():

var results = targetObject.map(function(obj){
      return Object.values(obj);
});
console.log(results);

Demo:

targetObject = [

{location: "MUGABALA  KOLAR ROAD", latitude: 13.108435679884, longitude: 77.890262391016},

{location: "pune", latitude: 18.6202008, longitude: 73.7908073},

{location: "RAJARAJESHWARI NAGAR BANGLORE", latitude: 12.901112992767, longitude: 77.5037757}

];

var results = targetObject.map(function(obj){
      return Object.values(obj);
});
console.log(results);

Object.values():

The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).



来源:https://stackoverflow.com/questions/44520500/how-to-convert-nested-object-into-array-of-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!