將數組對象相同key的內容合並


            function fireDuplicate (arr) {
                var arr = JSON.parse(JSON.stringify(arr))
                var ids = []
                arr.forEach(function(item) {
                    ids.push(item.id)
                })
                var newIds = []
                var newArr = []
                ids.forEach(function(id,index) {
                    var obj = {
                        id: '',
                        options: []
                    }
                    if (newIds.indexOf(id) > -1) {
                        var temp = newArr.find(function(item) {
                            return item.id == id
                        })
                        temp.options.push(arr[index].options[0])
                    } else {
                        obj.id = id
                        obj.options.push(arr[index].options[0])
                        newIds.push(id)
                        newArr.push(obj)
                    }
                })
                return newArr
            }    

例如原始數據:

const data = [
    {
        id: 1,
        content: [
            {name: 'peng'}
        ]
    },
    {
        id: 2,
        content: [
            {name: 'xing'}
        ]
    },
    {
        id: 1,
        content: [
            {name: 'yuan'}
        ]
    },
]

輸出結果:

const data = [
    {
        id: 1,
        content: [
            {name: 'peng'},
            {name: 'yuan'}
        ]
    },
    {
        id: 2,
        content: [
            {name: 'xing'}
        ]
    },
]

如果你有更好的方法實現,歡迎賜教,😀


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM