【问题标题】:How can i merge objects on the basis of same value in array of objects如何根据对象数组中的相同值合并对象
【发布时间】:2019-06-22 08:36:30
【问题描述】:

我有多个对象的数组。每个对象都有一个键“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'}]

【问题讨论】:

标签: javascript jquery arrays object


【解决方案1】:

这种方法有效:

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】:

    您可以通过查找具有相同 id 的对象来减少数组,并将该对象分配给 find 或获取一个新对象。

    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; }

    【讨论】:

      【解决方案3】:

      这里有一个解决方案

      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>

      【讨论】:

        猜你喜欢
        • 2012-12-19
        • 2020-02-08
        • 1970-01-01
        • 2021-09-12
        • 1970-01-01
        • 2019-10-07
        • 2018-04-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多