将数组对象相同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