javascript - 如何将多维数组移动到对象中
问题描述
嗨,我有这个来自 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" }
]
解决方案
使用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);
推荐阅读
- javascript - 如何粘贴带有样式元数据的文本内容
- automated-tests - 在使用 Cucumber、Selenium 和 Capybara 进行测试时,是否有一种简单的方法可以遍历嵌套的 Shadow DOM?
- firebase - 无论如何都可以将firebase存储用于flutter桌面吗?
- javascript - 动态更新 Web 组件脚本标记
- javascript -
- 元素类更改,使用 DOM
- html - 我的复选框和单选框与相关文本不对齐
- oracle - 添加索引后全局临时表数据不会被获取
- python - 使用 python mysqldb 连接器无密码通过 ssh 连接到远程 mysql 服务器
- c# - 如何在异常中发送函数的函数参数
- continuous-integration - [gitlab ci]:如何等待一个工作,只有这个工作已经开始,但如果它被跳过则不行