簡體   English   中英

lodash合並並組合對象

[英]lodash merge and combine objects

我有一個如下數組的對象,我使用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),但我遇到的主要問題是我有對象並且需要合並這個對象。

在普通的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()不那么冗長。

你可以這樣做( 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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM