首页 > 解决方案 > 如何将多维数组移动到对象中

问题描述

嗨,我有这个来自 json 的 javascript 数组,我想要下面使用 javascript 的预期输出?有人可以给一些方向。

[
    [{ "Key": 7, "Value": "Tours & experiances" }],
    [{ "Key": 6, "Value": "Theatre, dance and film" }],
    [
        { "Key": 2, "Value": "Children & family" },
        { "Key": 5, "Value": "Talks, course & workshops" }
    ],
    [{ "Key": 4, "Value": "Music" }],
    [{ "Key": 9, "Value": "Sports & fitness" }],
    [
        { "Key": 3, "Value": "Eat and drink" },
        { "Key": 8, "Value": "Shopping, markets & fairs" }
    ]
]

预期产出

[
    { "Key": 7, "Value": "Tours & experiances" },
    { "Key": 6, "Value": "Theatre, dance and film" },
    { "Key": 2, "Value": "Children & family" },
    { "Key": 5, "Value": "Talks, course & workshops" },
    { "Key": 4, "Value": "Music" },
    { "Key": 9, "Value": "Sports & fitness" },
    { "Key": 3, "Value": "Eat and drink" },
    { "Key": 8, "Value": "Shopping, markets & fairs" } 
]

标签: javascriptarrays

解决方案


使用flat将无限数量的嵌套数组转换为一个数组。

const data = [
  [{ "Key": 7, "Value": "Tours & experiances" }],
  [{ "Key": 6, "Value": "Theatre, dance and film" }],
  [
    { "Key": 2, "Value": "Children & family" },
    { "Key": 5, "Value": "Talks, course & workshops" }
  ],
  [{ "Key": 4, "Value": "Music" }],
  [{ "Key": 9, "Value": "Sports & fitness" }],
  [
    { "Key": 3, "Value": "Eat and drink" },
    { "Key": 8, "Value": "Shopping, markets & fairs" }
  ]
];

const result = data.flat(Infinity);
console.log(result);


推荐阅读