Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combine object data with an array of objects

By making two api calls receive two types of data as follows :

(1) array of Objects

[
  { label: "Private", price: 5 },
  { label: "VIP", price: 5 },
];

(2) Object >>>>> {}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
    "Private": {
        "count": 34
    },
    "VIP": {
        "count": 80
    }
}

How do I merge this data depending on the label to be as follows

[
  { label: "Private", price: 5, count: 34 },
  { label: "VIP", price: 5, count: 80 },
]

Thank you

>Solution :

Here is an easy way to merge those two into a new array of objects while not mutating your initial query results.

const array = [
  {label: "Private", price: 5},
  {label: "VIP", price: 5}
];

const object = {
  "Private": {"count": 34},
  "VIP": {"count": 80}
};

function merge(arr, obj) {
  // Create new array to avoid mutating initial query result
  const newArray = structuredClone(arr);
  newArray.forEach(item => {
    // Make sure obj has the label
    if (obj[item.label]) {
      // Simply assign the count by using key accessor syntax []
      item.count = obj[item.label].count;
    }
  });
  return newArray;
}

console.log(merge(array, object));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading