0

Hi I have a array of objects containing users with property uid and name and, I have one more array of objects this array contains uid and className. Now I want to apply these classes on users based on uid and if the uid is not present in classesArray then offline class should apply to all those users and these arrays are not sorted

userArray = [
  { uid: 11, uname: "nana" },
  { uid: 12, uname: "jack" },
  { uid: 17, uname: "wazir" },
  { uid: 15, uname: "cobra" },
  { uid: 16, uname: "janes" },
  { uid: 14, uname: "furan" },
  { uid: 13, uname: "arvind" },
];

classesArray = [
  { uid: 11, class: "online" },
  { uid: 14, class: "busy" },
  { uid: 13, class: "offline" },
  { uid: 12, class: "online" },
];

and i want the array like this:

MergedArray = [
  { uid: 11, unane: "nana", class: "online" },
  { uid: 12, unane: "jack", class: "online" },
  { uid: 13, unane: "arvind", class: "offline" },
  { uid: 14, uname: "furan", class: "busy" },
  { uid: 15, uname: "cobra", class: "offline" },
  { uid: 16, uname: "janes", class: "offline" },
  { uid: 17, uname: "wazir", class: "offline" },
];
1

1 Answer 1

3

You can use map and find like this:

const mergeArray = userArray.map((userItem) => {
  classesItem = classesArray.find((item) => item.uid === userItem.uid);
  return classesItem ? { ...userItem, class: classesItem.class } : {...userItem, class: "offline" };
});
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.