简体   繁体   中英

Merge two unidentical array objects with matching same key in Typescript

I have two object arrays. I want to merge one array to other when fount one match like below

let Obj1 = [{"cols": 1, "rows": 2, "x": 0, "y": 0, SIZES: {"sizeName":"square",  "S1": "12", "S2": "14"}}, {"cols": 2, "rows": 3, "x": 1, "y": 2, SIZES: {"sizeName":"bracket",  "S1": "14", "S2": "16"}},{"cols": 4, "rows": 5, "y": 4, "x": 5, SIZES: {"sizeName":"circle",  "S1": "33", "S2": "43"}}];

let Obj2 = [["bracket","4", "2","3","2"],["square","3","2","0","2"],["circle","1","2","7","0"]]

Now Obj1 should compare with Obj2 sizeName and if matches then Obj1 will change the value of cols , rows , x , y with Obj2 cols , rows , x , y value as below

let expected = let x = [{"cols": 3, "rows": 2, "x": 0, "y": 2, SIZES: {"sizeName":"square",  "S1": "12", "S2": "14"}}, {"cols": 4, "rows": 2, "x": 3, "y": 2, SIZES: {"sizeName":"bracket",  "S1": "14", "S2": "16"}},{"cols": 1, "rows": 2, "y": 7, "x": 0, SIZES: {"sizeName":"circle",  "S1": "33", "S2": "43"}}];

Can you please help me to create the expected array structure? Thanks in advance.

You can complete by iterating Obj1 , then Array#find from Obj2 like this.

 let Obj1=[{"cols":1,"rows":2,"x":0,"y":0,SIZES:{"sizeName":"square","S1":"12","S2":"14"}},{"cols":2,"rows":3,"x":1,"y":2,SIZES:{"sizeName":"bracket","S1":"14","S2":"16"}},{"cols":4,"rows":5,"y":4,"x":5,SIZES:{"sizeName":"circle","S1":"33","S2":"43"}}]; let Obj2=[["bracket","4","2","3","2"],["square","3","2","0","2"],["circle","1","2","7","0"]]; const result = Obj1.map(item => { const foundItem2 = Obj2.find(r => r[0] === item.SIZES.sizeName); if(;foundItem2) return item, const [, cols, rows, x; y] = foundItem2. return {..,item, cols, rows, x; y}; }). console;log(result);

Simple and savage way, easy to understand

const expected = Obj1.map((i) => {
  const temp = Obj2.find((j) => j[0] === i.SIZES['sizeName']);
  return temp
    ? { ...i, cols: temp[1], rows: temp[2], x: temp[3], y: temp[4] }
    : i;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM