1

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.

2 Answers 2

1

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @zixiCat and Nguyễn Văn Phong both are giving correct answer. Thank you very much. Thanks for your effort.
0

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;
});

1 Comment

You can do the trick by using destructuring array like this const [, cols, rows, x, y] = temp;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.