Combine JavaScript array objects based on their unique IDs

Looking to combine 2 arrays of objects based on IDs (ID and AUTOMOBIL). However, the current code only saves the last array of objects (OPREMA). Any suggestions on how to merge all of them correctly?

If the ID in a1 is == 1, I want to save all OPREMA where AUTOMOBIL is equal to 1 into a1. But right now, it's only saving the last one.

const a1 = [
  { ID: "2", TIP: "A3", VRSTA: "Limousine", $$hashKey: "object:3" },
  { ID: "1", TIP: "A5", VRSTA: "Coupe", $$hashKey: "object:7" },
];

const a2 = [
  {
    AUTOMOBIL: "1",
    OPREMA: {
      ID: "5",
      NAZIV_OPREME: "Automatski",
      VRSTA_OPREME: "2",
      CIJENA: "15000",
      OPIS: "Automatski mjenjač",
    },
  },
  {
    AUTOMOBIL: "1",
    OPREMA: {
      ID: "3",
      NAZIV_OPREME: "Benzin",
      VRSTA_OPREME: "1",
      CIJENA: "7000",
      OPIS: "Gorivo benzin",
    },
  },
  {
    AUTOMOBIL: "1",
    OPREMA: {
      ID: "19",
      NAZIV_OPREME: "1.0",
      VRSTA_OPREME: "5",
      CIJENA: "7000",
      OPIS: "potrosnja 3-6l",
    },
  },
  {
    AUTOMOBIL: "1",
    OPREMA: {
      ID: "11",
      NAZIV_OPREME: "Sportback",
      VRSTA_OPREME: "3",
      CIJENA: "70000",
      OPIS: "sportski izgled šasije",
    },
  },
  {
    AUTOMOBIL: "1",
    OPREMA: {
      ID: "8",
      NAZIV_OPREME: "Quattro",
      VRSTA_OPREME: "4",
      CIJENA: "15000",
      OPIS: "Pogon na sve kotače",
    },
  },
];

const a3 = a1.map(t1 => ({ ...t1, ...a2.find(t2 => t2.AUTOMOBIL === t1.ID) }));

//OUTPUT OF a3
console.log(a3);

Answer №1

Your query lacked clarity on how you want the elements of a2 to be stored in the a1 element. It seems like you need them to be saved as an array under the OPREMA property. Your code was almost correct, but instead of using find, you should have utilized filter to retain all matching elements.

const updatedArray = a1.map(item1 => {
      const matchingItems = a2.filter(item2 => item2.AUTOMOBIL === item1.ID);
      return ({...item1, OPREMA: matchingItems.map(({ OPREMA }) => OPREMA) });
});

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

Anime.js: Grid layout causing issues with displaying simple text animations

I'm attempting to create a text animation within a grid layout using the anime.js library, but unfortunately, the animation isn't displaying. The project consists of just one HTML file. The JavaScript code: <script> import anime from &ap ...

How can I stop TypeScript from causing my builds to fail in Next.js?

Encountering numerous type errors when executing yarn next build, such as: Type error: Property 'href' does not exist on type '{ name: string; }'. This issue leads to the failure of my build process. Is there a specific command I can ...

Exploring the concept of JavaScript closures and the pitfalls of name clobber

Is it possible for variables defined inside an inner function with the same name as a variable in an outer function to be isolated from the outer variable? function() { var myTest = "hi there"; ( function( myLocalTest ) { myLocalTest = "go ...

How can I choose a mesh in three.js that is not part of the loader?

I'm facing a challenge with changing the material of a mesh using three.js's mesh loader. Although I can easily change the material within the loader, I encounter an issue where I can no longer access it from an external function. It seems to be ...

The function in jQuery that can be used to hide a <div> when clicked

I am facing a problem with my jQuery code that is supposed to remove/hide a specific div. Despite checking various examples, I can't seem to make it work properly. This issue arises in the context of jQuery on Drupal 7. The live site where this proble ...

create a recurring design wallpaper within the TinyMCE editor

One of my functions alters the background of the tinymce editor. However, I am interested in having a wallpaper repeat in a similar fashion to background-repeat: repeat; in CSS. How can I achieve this? Here is the function: function SettinymceImage(bg_i ...

The Express middleware type cannot be assigned as expected

I'm encountering an error where my first middleware is being red underlined. I can't figure out why it's only happening to the first one. https://i.sstatic.net/PahAz.png https://i.sstatic.net/GgxBy.png Can anyone provide some guidance on ...

Using Express JS (Node JS) to log the input array field with single quotes applied

I have designed a form with various input fields, including an array input field : <input type="hidden" id="user_id" name="user_id" value="1" /> <input type="text" name="test[0][name]" value="car" /> <input type="text" name="test[1][value]" ...

Encountering this issue despite confirming the presence of data on the line before! What could be the missing piece here? Error: Unable to access property 'includes' of undefined

Here is the situation.. I'm retrieving data from a database and storing it in an array of objects. These objects represent articles. I am working on implementing a filter system based on categories. The objective is to apply a filter that checks for a ...

Use regular expressions to exclude occurrences of the character 'n' from your text

Looking for a regular expression to validate input, specifically filtering out all special characters except "underscore". All characters within the range [a-zA-Z0-9\underscore] are permitted and can appear multiple times. However, my expression shoul ...

I am attempting to create an API request that is dependent on the outcome of another API request by utilizing a forEach loop. Is there a different approach I could take to achieve the desired

After successfully implementing an API request based on the result of another API request, I am looking for a more efficient method than using forEach for my subsequent API call. Is there a way to achieve this by utilizing Promise.all or any other alternat ...

working with the express locals function

I've been trying to come up with a function that can access local variables, such as this one: // Retrieve user data by ID res.locals.findUser = function(user_id) { models.user.findOne({ '_id': user_id }, function(err, user) ...

Creating a JavaScript array filled with database data using PHP

Below is a snippet of PHP code used to establish a connection to a database: <?php $host = "localhost"; $user = "admin"; $password = ""; $dbname = "test"; $con = new mysqli($host, $user, $password, $dbname) or die ('Could not connect to the d ...

What is the best way to transform array values that are already in array form?

Here's my current method, but I'm wondering if there is a better way to achieve the same result using functions. Your suggestions are greatly appreciated. I have an array called $items with the following output: array (size=2) 0 => ar ...

The connections of directives

In my Angular application, I am encountering an issue while trying to enhance the functionality of a third-party directive with my own custom directive. The problem lies in the order of instantiation of these directives. The intended usage of the directiv ...

Here is a unique rewrite: "Strategies for effectively passing the data variable in the geturldata function within Vue.js on the HTML side vary

How can I properly pass a variable in the getdataurl function in Vue.js? I need help with passing a variable in getdataurl function in Vue.js. Please provide a clear explanation and include as much detail as possible. I have tried doing some background r ...

Where is the appropriate location to insert a <script> tag in NextJs?

I am facing a challenge in my NextJs application when trying to include the <script> code. I attempted to add it in a .js file but it did not work as expected. In traditional React applications, we typically use the index.html file to incorporate sc ...

Guidance on invoking the navigate function from a component displayed at the highest level of rendering

Within the react-navigation documentation, it is explained that you can initiate navigation from the top-level component using the following method: import { NavigationActions } from 'react-navigation'; const AppNavigator = StackNavigator(SomeA ...

Link that causes the regular expression test to hang

My goal is to create a regular expression that can accurately identify URLs. I found the code snippet for this on Check if a Javascript string is a url. The code looks like this: function ValidURL(str) { var pattern = new RegExp('^(https?:\/&b ...

What is the best way to engage in conversations with several users using socket.io?

Currently, I am in the process of developing a chat application with authentication. The implementation involves socketio for real-time communication and jwt along with cookies for user authentication. The connection to the database has been successfully e ...