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

Push elements of

This is, I believe a very simple question for a JS programmer. Given the following array of objects named "categories"

[
    {
        "id": 1,
        "name": "FURNITURE", 
    },
    {
        "id": 2,
        "name": "AUTOMOTIVE",
    },
    {
        "id": 3,
        "name": "UPHOLSTERY",
    }
]

I want to push the "name" on the "selectedCategories" array below where "id" === "id"

[
    {
        "id": 1
    },
    {
        "id": 3
    }
]

Below is my attempt to solve this, but … not working..

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

for (let i = 0; i < selectedCategories.length; i++) {
    for(let y = 0; y < categories.length; y++){
      selectedCategories.name = categories[y].name
    }
  }

>Solution :

I believe this is what you are looking for

selectedCategories = selectedCategories.map(el => {
    const searchEl = categories.find(e => e.id === el.id);
    if (searchEl)
        return { ...el, name: searchEl.name }
    return el;
});
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