lodash 合并和合并对象

lodash merge and combine objects

我有一个对象数组,如下所示,我使用 sequelize ORM 从我的数据库中读取了这些对象: 我想从一个部分获得我的所有视频,但我可以 return 使用 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) 但我遇到的主要问题是我有一个对象并且需要合并这个对象。

你可以这样做(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.

在普通 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>');

也许试试 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() 不那么冗长。