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

Merged object into Array of object with same key

I am looking to merge the object with the same key in an array of objects.

I have the first object structure like this

   const cultures = {
     "en-us": {
       "path": "/en/playground/copy/",
       "startItem": {
         "id": "8cd7943c-1ba5-41cb-a9ac-7435fbdb1458",
         "path": "path"
       }
     },
     "da-dk": {
       "path": "/playground/copy/",
       "startItem": {
         "id": "8cd7943c-1ba5-41cb-a9ac-7435fbdb1458",
         "path": "path"
       }
     }
   }

And I have the second array of object like this

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

const lang = [
      {
        name: 'English',
        isoCode: 'en-us',
        url: '/en/'
      },
      {
        name: 'Danish',
        isoCode: 'da-dk',
        url: '/'
      }
    ]

I want to get just the path of the first object and merged in the array of objects with same key. Would it be possible to achieve something like this?

[
  {
    name: 'English',
    isoCode: 'en-US',
    url: '/en/',
    path: "/en/playground/copy/",
    
  },
  {
    name: 'Danish',
    isoCode: 'da-DK',
    url: '/',
    path: "/playground/copy/",
    
  }
]

I tried this and returns false always.

languages.filter((item, i) => {
      const arr = [];
      const result = item.isoCode === data.cultures[item.isoCode];

      arr.push(result);
    });

>Solution :

You need to map new objects with new path property.

const
    cultures = { "en-us": { path: "/en/playground/copy/", startItem: { id: "8cd7943c-1ba5-41cb-a9ac-7435fbdb1458", path:  "path" } }, "da-dk": { path: "/playground/copy/", startItem: { id: "8cd7943c-1ba5-41cb-a9ac-7435fbdb1458", path:"path" } } },
    lang = [{ name: 'English', isoCode: 'en-us', url: '/en/' }, { name: 'Danish', isoCode: 'da-dk', url: '/' }],
    result = lang.map(o => ({ ...o, path: cultures[o.isoCode].path }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
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