我想在JavaScript中将JSON转换为数组

问题描述 投票:-1回答:1

我有一个JSON,如下所示:

{
  "83" : {
    "firstColumn" : 78,
    "secondColumn" : 76,
    "thirdColumn" : 51
  },
  "390" : {
    "firstColumn" : 48,
    "secondColumn" : 25,
    "thirdColumn" : 45
  },
  "454" : {
    "firstColumn" : 96,
    "secondColumn" : 55,
    "thirdColumn" : 65
  },
  "524" : {
    "firstColumn" : 0,
    "secondColumn" : 23,
    "thirdColumn" : 18
  }
}

我想将其转换为数组

javascript
1个回答
2
投票

您可以使用Object.values()将其转换为没有孔的数组,并根据数字键值进行排序:

const obj = { "83" : { "firstColumn" : 78, "secondColumn" : 76, "thirdColumn" : 51 }, "390" : { "firstColumn" : 48, "secondColumn" : 25, "thirdColumn" : 45 }, "454" : { "firstColumn" : 96, "secondColumn" : 55, "thirdColumn" : 65 }, "524" : { "firstColumn" : 0, "secondColumn" : 23, "thirdColumn" : 18 } }

const array = Object.values(obj)

console.log(array)

可能适合边缘情况的不太明显的选择是创建一个稀疏数组。稀疏数组是具有未分配索引的数组。在这种情况下,项目将位于与属性的数值匹配的索引中。我们可以使用Array.from(),但是您需要提供长度。一个可靠的假设是采用最高的键数字值并加1,您可以使用Math.max(...Object.keys(obj)) + 1

const obj = { "83" : { "firstColumn" : 78, "secondColumn" : 76, "thirdColumn" : 51 }, "390" : { "firstColumn" : 48, "secondColumn" : 25, "thirdColumn" : 45 }, "454" : { "firstColumn" : 96, "secondColumn" : 55, "thirdColumn" : 65 }, "524" : { "firstColumn" : 0, "secondColumn" : 23, "thirdColumn" : 18 } }

const array = Array.from({ ...obj, length: Math.max(...Object.keys(obj)) + 1 })

console.log(array)
© www.soinside.com 2019 - 2024. All rights reserved.