lodash合并并组合对象

时间:2016-02-29 10:31:40

标签: javascript sequelize.js lodash

我有一个对象数组如下所示,我使用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 个答案:

答案 0 :(得分: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>');

答案 1 :(得分: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()不那么详细。

答案 2 :(得分:0)

你可以这样做(test是你的db输出)

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.