我如何基于对象数组中的相同值合并对象

时间:2019-06-22 08:36:30

标签: javascript jquery arrays object

我有多个对象的数组。每个对象都有一个键“ id”。我想基于相同的“ id”值合并对象。

var obj = [{'id': 1, 'title': 'Hi'}, {'id': 1, 'description': 'buddy'}, {'id': 2, 'title': 'come'}, {'id': 2, 'description': 'On'}]

And i want output something like that

var new_obj = [{'id': 1, 'title': 'Hi' 'description': 'buddy'}, {id: 2, 'title': 'come', 'description': 'on'}]

3 个答案:

答案 0 :(得分:0)

您可以通过查找具有相同id的对象来缩小数组,然后将该对象分配给找到的对象或采用新的对象。

var array = [{ id: 1, title: 'Hi' }, { id: 1, description: 'buddy' }, { id: 2, title: 'come' }, { id: 2, description: 'On' }],
    result = array.reduce((r, o) => {
        var temp = r.find(({ id }) => o.id === id);
        if (!temp) r.push(temp = {});
        Object.assign(temp, o);
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

这种方式有效:

let toMerge = [{'id': 1, 'title': 'Hi'}, {'id': 1, 'description': 'buddy'}, {'id': 2, 'title': 'come'}, {'id': 2, 'description': 'On'}]
let merged = []

for ( let object of toMerge ) {
    // if object not already merged
    if(!merged.find(o => o.id === object.id)) {
        // filter the same id's objects, merge them, then push the merged object in merged array
        merged.push(toMerge.filter(o => o.id === object.id).reduce((acc, val) => {return {...acc, ...val}}))
    }
}

答案 2 :(得分:-1)

这是一个解决方案

const data = [
    {
        id: 1,
        title: "Hi"
    },
    {
        description: "buddy",
        id: 1
    },
    {
        id: 2,
        title: "come"
    },
    {
        description: "On",
        id: 2
    }
]

const f = (data) => 
  Object.values(data.reduce(
    (y, x) => ({
      ...y, 
      [x.id]: {
        ...x, 
        ...(y[x.id] || {})
      },
    }),
    {},
  ))
console.log(f(data))

这是使用Ramda.js的解决方案

const data = [
    {
        id: 1,
        title: "Hi"
    },
    {
        description: "buddy",
        id: 1
    },
    {
        id: 2,
        title: "come"
    },
    {
        description: "On",
        id: 2
    }
]

const f = R.compose(R.values, R.reduceBy(R.merge, {}, R.prop('id')))

console.log(f(data))
<script src="//cdn.jsdelivr.net/npm/ramda@latest/dist/ramda.min.js"></script>