javascript - 如何重新格式化嵌套的数据数组?
问题描述
我正在尝试重新格式化这个数组
const array =[
[
{name: 'John', score: 78},
{name: 'Peter', score: 88}
],
[
{name: 'John', score: 98},
{name: 'Peter', score: 80}
]
]
进入这个
newArray = [['约翰', 78, 98], ['彼得', 88, 80]]
我能做的就是这样
let name = []
let score = []
for (var i = 0; i < array.length; i++) {
const detail = array[i]
for (var j = 0; j < detail.length; j++) {
name.push(detail[j].name)
}
for (var j = 0; j < detail.length; j++) {
scoreArray = detail[j].score
score.push(scoreArray)
}
}
const newArray= name.concat(score)
并给我结果
["John", "Peter", "John", "Peter", 78, 88, 98, 80]
解决方案
const array =[
[
{name: 'John', score: 78},
{name: 'Peter', score: 88}
],
[
{name: 'John', score: 98},
{name: 'Peter', score: 80}
]
]
// get the unique names
const names = [...new Set(...array.reduce((acc, item) => {
return [...acc, item.map(i => [i.name])]
}, []))]
// add the scores next to the names
array.flat().forEach((el) => {
names.forEach(([name], index) => {
if (el.name === name) {
names[index].push(el.score)
}
})
})
console.log(names)
但我认为你最好这样做:
const array =[
[
{name: 'John', score: 78},
{name: 'Peter', score: 88}
],
[
{name: 'John', score: 98},
{name: 'Peter', score: 80}
]
]
const result = [...new Set(...array.reduce((acc, item) => {
return [...acc, item.map(i => ({name: i.name, scores: []}))]
}, []))]
// add the scores next to the names
array.flat().forEach((el) => {
result.forEach(({name, scores}, index) => {
if (el.name === name) {
scores.push(el.score)
}
})
})
console.log(result)
并将名称和分数存储到自己的密钥中。
推荐阅读
- php - PHP算术运算给出错误结果
- linux - vim 自定义键绑定中的括号有什么作用?
- javascript - 保存时更漂亮的 VSCODE 重新格式化已停止工作
- mongodb - 一个集合中的mongodb地图数据
- python - 代码不解码通过python中的套接字发送的消息
- python-3.x - 如何从现有列中添加分类列(Python 中的分类数据)
- php - 将“WooCommerce”仪表板菜单选项名称更改为“商店”
- ios - Nativescript 检测方向而不自动旋转屏幕内容
- python - python中的字符串连接使用不同的方法占用指数内存
- c# - 多个带有代理的 HttpClients,试图达到最大的下载速度