2016-02-29 124 views
3

我有對象下面,我用sequelize ORM從我的數據庫中讀出的數組: 我想有從部分我所有的影片,但我可以返回使用sequelize更好的是:lodash合併,合併對象

[{ 
    "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(對象來源,定製),但我的主要問題是我有對象,需要合併是對象。

回答

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. 
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()更簡潔。

+0

我會盡我所能,解決方案是優雅的幾行。 – Aaleks

+0

工作完美! – Aaleks