ecmascript 6 - Create a new map from an array of object with similar id in Typescript -
i'm trying create map> list of objects have similar ids in typescript, don't correct way do. know in lodash doable can't work. have tried
let's have list of colors so:
[ { "id": "1", "color": "red", "ref": "tr" }, { "id": "1", "color": "blue", "ref": "gt", }, { "id": "2", "color": "red", "ref": "tt" }, ] i'm trying construct map so
[ 1: [ { "id": "1", "color": "red", "ref": "tr" }, { "id": "1", "color": "blue", "ref": "gt", } ], 2: [ { "id": "2", "color": "red", "ref": "tt" } ] ] this tried far:
const colorsmap: map<string, array<color>> = new map<string, array<color>>(); let colorlists: array<color> = []; colors.foreach(function (value, i) { if (value[i - 1]) { if (colors[i - 1].id=== value.gblid) { const color = new color(value.styleid, value.color, value.ref); colorlists.push(gblrowvalue); } else { const color = new color(value.styleid, value.color, value.ref); colorlists= new array<color>(); colorlists.push(color); } } colorsmap.set(value.id, colorlists); }); the result in each array 1 value:
[ 1: [ { "id": "1", "color": "blue", "ref": "gt", } ], 2: [ { "id": "2", "color": "red", "ref": "tt" } ] ]
in case can use es6 features, use following small snippet, not require huge lodash library:
let colors = [ { "id": "1", "color": "red", "ref": "tr" }, { "id": "1", "color": "blue", "ref": "gt", }, { "id": "2", "color": "red", "ref": "tt" }, ]; let orderedcolors = colors.reduce((returnarray, color) => { if(!returnarray[color.id]){ returnarray[color.id] = []; } returnarray[color.id].push(color); return returnarray; },[]);
Comments
Post a Comment