Combining objects into an array of objects with matching keys

Seeking to combine objects with the same key within an array of objects.

The initial object structure is as follows:

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

Next, the array of objects looks like this:

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

The goal is to extract the path from the first object and merge it into the array of objects by matching keys. Is there a way to achieve this?

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

An attempt was made using the following code snippet but it consistently returns false:

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

      arr.push(result);
    });

Answer №1

You are required to create mappings for new objects that include a new path property.

const
    cults = { "en-us": { path: "/en/playground/copy/", beginItem: { id: "8cd7943c-1ba5-41cb-a9ac-7435fbdb1458", route:  "path" } }, "da-dk": { path: "/playground/copy/", beginItem: { id: "8cd7943c-1ba5-41cb-a9ac-7435fbdb1458", route:"path" } } },
    language = [{ name: 'English', code: 'en-us', link: '/en/' }, { name: 'Danish', code: 'da-dk', link: '/' }],
    result = language.map(obj => ({ ...obj, path: cults[obj.code].path }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with Jquery UI sortables not functioning properly

Struggling with getting a sortable list to work using jQuery UI. The ul element is receiving the class 'ui-sortable' but nothing seems to be happening. To demonstrate this issue, I created an example since the original javascript code is quite c ...

Displaying a single image on various surfaces of a BoxGeometry in Three.js

I am currently utilizing three.js to generate 3D Objects. My goal is to develop a 3D canvas similar to the one showcased here in my project. I aim to display a single image on all sides of the object (box) except for the back. I came across a relevant exa ...

What is the best way to save the city name received from geolocation into a variable and then make an AJAX request?

<script> new Vue({ el: '#fad' , data: { data: {}, }, mounted() { var self = this; navigator.geolocation.getCurrentPosition(success, error); function success(position) { var GEOCO ...

Creating an ArrayList of Integers in Java: A Step-by-Step Guide

I encountered an issue while trying to create an array of ArrayLists in my code. Here is what I attempted: ArrayList<Integer>[]list=new ArrayList<Integer>[128]; However, Eclipse displayed the following error message: Cannot create a generi ...

Exploring TypeScript: Implementing a runtime data mapping in place of an interface

Take a look at this code snippet that defines two command handlers for a server: import { plainToClass } from "class-transformer"; enum Command { COMMAND_1, COMMAND_2, } class Command1Data { foo1!: string } class Command2Data { foo2!: ...

When there is an expensive calculation following a Vue virtual DOM update, the update may not be

Currently, I am facing an issue with adding a loading screen to my app during some heavy data hashing and deciphering processes that take around 2-3 seconds to complete. Interestingly, when I removed the resource-intensive parts, the screen loads immediate ...

The necessity for one type argument is apparent in a generic type, particularly when it is divided into a distinct type

I have a simple scenario that resembles the following and is functioning perfectly: export interface CustomState { someBool: boolean; status: string; } function checkStateDifference<K extends keyof CustomState>(props: { stateKey: K, value: Custo ...

How can you pair a collection of foreign keys in one table with the primary key in another table?

I have two tables. The first one is structured like this: id | array_of_ids ---------------------- 001 | {012, 345, 789} 002 | {789, 123, 456} 003 | {234, 789, 567} 004 | {543, 210, 789} The second table looks like this: ids | str ------------- ...

The form will only send a single file or image

I'm facing an issue with uploading multiple images. I've tried various solutions but none of them seem to be working. Front-end Code Below is my PUG code snippet: form#new-shortcut.form-horizontal.elegant-color-dark(action='/themes/new?_c ...

Creating a comparison display using ng-repeat

I have a JSON file that contains revision and history information about a modified entity, including its old and new values. The diff is generated using the jsondiffpatch library and I have parsed it further to create the final JSON format for rendering. ...

Navigate to the subsequent field in an HTML5 form without any manual intervention

I have created the following HTML5 form: <form> <input type="text" name="orderno" /> <input name="picture" id="img" type="file" accept="image/*" capture="camera" /> <input class="btn-success" type="submit" name="submit" value="Uplo ...

Having difficulty validating the field accurately with Angular.js

In order to validate the input field in accordance with the user's needs using AngularJS, I have shared my code below: <div ng-class="{ 'myError': billdata.longitude.$touched && billdata.longitude.$invalid }"> <input type ...

Create a new build for testing and debugging using create-react-app

Currently, I am in the process of developing a web application that utilizes a React frontend and is powered by a golang api layer. Although I do not have extensive experience with Javascript, I find myself struggling with the Node build system. I am loo ...

Understanding complex JSON data structures in MySQL

Can anyone recommend a plugin that efficiently parses multidimensional JSON strings in MySQL like it can be done in MSSQL? { something : [{ somethingElse : [{ awesome : true }] }], [{ somethingDifferent : [{ awesome : false, m ...

KineticJS: Applying a filter to an image does not result in the image having a stroke

Working with KineticJS version 5.1.0 I encountered an issue where a KineticJS image that had a stroke lost the stroke after applying a filter to it. I have created a demo showcasing this problem, which can be viewed on JSFiddle. Here is the code snippet: ...

Returning a set of indexes for two elements in an array that combine to equal a specified target sum

For my current project, I've been tasked with writing a function that accepts an array of numbers along with a target number. The goal is to identify two numbers in the array that can be added together to reach the target value, and then return the i ...

Is it possible to securely embed videos on external websites while also utilizing tokens to safeguard the content?

Protecting our video content on our website is a top priority, which is why we have implemented a system where a token is grabbed through AJAX and verified through PHP before allowing the download of any files. As I delve into providing an embed feature s ...

Leveraging deep linking to launch the email application in react native

I am currently exploring the deeplink URL for the mail app on iOS. A scenario I have set up involves displaying an alert that, when the user clicks 'ok', redirects them to the default mail app. const openEmailApp = () => { if (Platform.OS ...

What role does enum play in typescript?

What is the purpose of an enum in typescript? If it's only meant to improve code readability, could we achieve the same result using constants? enum Color { Red = 1, Green = 2, Blue = 4 }; let obj1: Color = Color.Red; obj1 = 100; // IDE does not sh ...