0

I'm trying to change some properties in the first array of objects based on the second array of objects

here is the first one

const data1 = [
  {
    type: 'text',
    message: 'Hi',
    area: 'A',
  },
  {
    type: 'text',
    message: 'Bye',
    area: 'B',
  },
  {
    type: 'text',
    message: 'Yeah',
    area: 'C',
  },
];

and the second one is

const data2 = [
  {
    area: {
      a: 1,
    },
  },
  {
    area: {
      b: 2,
    },
  },
  {
    area: {
      c: 3,
    },
  },
];

here is my expect result

const result = [
  {
    type: 'text',
    message: 'Hi',
    area: {
      a: 1,
    },
  },
  {
    type: 'text',
    message: 'Bye',
    area: {
      b: 2,
    },
  },
  {
    type: 'text',
    message: 'Yeah',
    area: {
      c: 3,
    },
  },
];

This is what I've done so far,

let a = data1.map((item, idx) => {
  return { ...item, ['area']: data2[idx] };
});

but it doesn't work as expected, please advice.

1 Answer 1

1

area of data2 is destructed later, so it will override the area of data1

Below snippet could help you

const data1 = [{
    type: "text",
    message: "Hi",
    area: "A",
  },
  {
    type: "text",
    message: "Bye",
    area: "B",
  },
  {
    type: "text",
    message: "Yeah",
    area: "C",
  },
]

const data2 = [{
    area: {
      a: 1,
    },
  },
  {
    area: {
      b: 2,
    },
  },
  {
    area: {
      c: 3,
    },
  },
]

const res = data1.map((elem, i) => ({
  ...elem,
  ...data2[i],
}))

console.log(res)

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

Comments

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.