Lodash合并和组合对象

3

我有一个对象数组,如下所示,我使用sequelize ORM从我的数据库中读取: 我想要从一个部分获取所有的视频,但是我能够使用sequelize返回更好的结果:

[{
    "id": 2,
    "name": "Ru",
    "subsection": 1,
    "Video": {
      "id": 11,
      "source": "sourrrccrsss22222",
      "videoSubSection": 2
    }
  },
  {
    "id": 2,
    "name": "Ru",
    "subsection": 1,
    "Video": {
      "id": 12,
      "source": "sourrrccrsss111",
      "videoSubSection": 2
    }
  },
  {
    "id": 1,
    "name": "Oc",
    "subsection": 1,
    "Video": {
      "id": 13,
      "source": "sourrrcc",
      "videoSubSection": 1
    }
  },
  {
    "id": 1,
    "name": "Oc",
    "subsection": 1,
    "Video": {
      "id": 14,
      "source": "sourrrcc",
      "videoSubSection": 1
    }
  }]

有没有一种方法可以合并和组合我的数组中的对象,以获得这样的结果:
[{
    "id": 2,
    "name": "Ru",
    "subsection": 1,
    "Video": [{
      "id": 11,
      "source": "sourrrccrsss22222",
      "videoSubSection": 2
    },{
      "id": 12,
      "source": "sourrrccrsss111",
      "videoSubSection": 2
    }]
  },
  {
    "id": 1,
    "name": "Oc",
    "subsection": 1,
    "Video": [{
      "id": 13,
      "source": "sourrrcc",
      "videoSubSection": 1
    },{
      "id": 14,
      "source": "sourrrcc",
      "videoSubSection": 1
    }]
  }

我最喜欢的函数是_.mergeWith(object, sources, customizer),但我遇到的主要问题是我有一个对象,需要合并这个对象。
3个回答

1
也许尝试使用transform()
_.transform(data, (result, item) => {
  let found;

  if ((found = _.find(result, { id: item.id }))) { 
    found.Video.push(item.Video);
  } else {
    result.push(_.defaults({ Video: [ item.Video ] }, item));
  }
}, []);

在这里使用 reduce() 也可以,但 transform() 更加简洁。

我会尽力而为,这个解决方案简洁优雅,代码行数很少。 - Aaleks
工作得非常完美! - Aaleks

1
在纯Javascript中,您可以使用 Array#forEach() 和一个临时对象来处理数组。

var data = [{ id: 2, name: "Ru", subsection: 1, Video: { id: 11, source: "sourrrccrsss22222", VideoSubSection: 2 } }, { id: 2, name: "Ru", subsection: 1, Video: { id: 12, source: "sourrrccrsss111", VideoSubSection: 2 } }, { id: 1, name: "Oc", subsection: 1, Video: { id: 13, source: "sourrrcc", VideoSubSection: 1 } }, { id: 1, name: "Oc", subsection: 1, Video: { id: 14, source: "sourrrcc", VideoSubSection: 1 } }],
    merged = function (data) {
        var r = [], o = {};
        data.forEach(function (a) {
            if (!(a.id in o)) {
                o[a.id] = [];
                r.push({ id: a.id, name: a.name, subsection: a.subsection, Video: o[a.id] });
            }
            o[a.id].push(a.Video);
        });
        return r;
    }(data);

document.write('<pre>' + JSON.stringify(merged, 0, 4) + '</pre>');


0
你可以这样做(test 是你的数据库输出)
var result = [];
var map = [];

_.forEach(test, (o) => {
  var temp = _.clone(o);
  delete o.Video;
  if (!_.some(map, o)) {
    result.push(_.extend(o, {Video: [temp.Video]}));
    map.push(o);
  } else {
    var index = _.findIndex(map, o);
    result[index].Video.push(temp.Video);
  }
});

console.log(result); // outputs what you want.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接