Question:
How to merge an object into Array with the same key in JavaScript?

Problem:

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

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; }


Suggested blogs:

>How can I browser to render links in streamed content in Django?

>Access the "model" attribute for a ListView in Django for template

>How to use a function to print S3 data to HTML using Django?

>How to make a code executed after an entry is inserted, removed or updated?

>How to insert new data into the table in Django?

>Disabling default ordering in the Django admin panel

>How to migrate `DateTimeField` to `DateField` in Django?


Ritu Singh

Ritu Singh

Submit
0 Answers