hi, 欢迎访问我的博客

将数组对象相同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'}
        ]
    },
]

如果你有更好的方法实现,欢迎赐教,😀

posted @ 2019-01-02 18:06  打静爵  阅读(2161)  评论(0编辑  收藏  举报