如何将嵌套对象转换为数组数组

时间:2017-06-13 11:41:00

标签: javascript jquery arrays node.js object

您好我想将array of object转换为array of array

这是我的有针对性的 array objects看起来像这样

(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)

我认为它的结构如下:

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}

];

我想要的输出:

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

              ["pune",  18.6202008, 73.7908073],

            ["RAJARAJESHWARI NAGAR BANGLORE", 12.901112992767, 77.5037757]

];

2 个答案:

答案 0 :(得分:2)

您可以映射Object.values的结果。

对于旧版用户代理,您可以使用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; }




答案 1 :(得分:2)

您可以使用Object.values() Array.prototype.map() 执行此操作:

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);

<强>演示:

&#13;
&#13;
{{1}}
&#13;
&#13;
&#13;

<强> Object.values()

  

Object.values()方法返回给定对象自身的可枚举属性值的数组,其顺序与for ... in循环提供的顺序相同(不同之处在于for-in loop枚举原型链中的属性。)