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

Posted

技术标签:

【中文标题】如何将嵌套对象转换为数组数组【英文标题】:how to convert nested object into array of array 【发布时间】:2017-11-15 04:09:18 【问题描述】:

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

这是我的目标 array of 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]

];

【问题讨论】:

targetObject.map(x=> Object.keys(x).map(k=> x[k]) ) 参考这里:***.com/questions/41427699/… 【参考方案1】:

你可以映射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; 

【讨论】:

注意:Object.values 是一项实验性技术【参考方案2】:

您可以使用Object.values()Array.prototype.map()

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

演示:

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

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

【讨论】:

以上是关于如何将嵌套对象转换为数组数组的主要内容,如果未能解决你的问题,请参考以下文章

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

如何将嵌套的 JSON 对象转换为数组 Spring Boot?

将平面对象数组转换为嵌套对象数组[重复]

将嵌套对象数组转换为对象数组的最佳方法

如何将树状的数组和对象的嵌套数据结构转换为具有计算/计数 id 和跟踪父 id 的项目列表?

将嵌套对象转换为数组