首页 > 解决方案 > 如何重新格式化嵌套的数据数组?

问题描述

我正在尝试重新格式化这个数组

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]

标签: javascript

解决方案


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)

并将名称和分数存储到自己的密钥中。


推荐阅读