Combining JavaScript JSON objects with corresponding parameters

I'm struggling to find a solution for merging two JSON objects. Despite searching for answers, I haven't found any that have been helpful. My goal is to compare two objects and if there's a match, add an attribute as a marker to the first object. Here's an example:

Fiddle: https://jsfiddle.net/aunzyfcj/

First input object:

    var firstInput = [{
        "id": "43", 
        "published": "yes", 
        "publish_date": "20.08.2019"

      }, {
        "id": "44",
        "published": "yes", 
        "publish_date": "20.08.2019"         
     }]

Second input object:

    var secondInput = [{
        "id": 92,
        "id_artikla": "140"
    }, {
        "id": 93,
        "id_artikla": "139"
    }, {
        "id": 94,
        "id_artikla": "44"
    }, {
        "id": 95,
        "id_artikla": "10"
    }, {
        "id": 96,
        "id_artikla": "12"
    }, {
        "id": 97,
        "id_artikla": "22"
    }, {
        "id": 98,
        "id_artikla": "9"
    }]  

I want to check if the "id": "44" from the firstInput object exists in the "list" of the secondInput object and create a third output object with a copy of (same length) the firstInput, but this time adding the attribute "status": "SAVED" if the "id": "44" exists in secondInput as "id_artikla": "44".

If there's no match, I'd like to add the attribute "status": "SAVE_ME". Please see the output example below.

Output object:

     var output =  [{
        "id": "43", 
        "published": "yes", 
        "publish_date": "20.08.2019",
        "status": "SAVE_ME"
      }, {
        "id": "44",
        "published": "yes", 
        "publish_date": "20.08.2019",
        "status": "SAVED"
     }]

I've attempted using the code below, but it doesn't give me the desired output. It only adds one matching id.

            let i = 0;
            firstInput.forEach( function( item ) {         
                 var artikal = item.id; 
                 secondInput.forEach( function( data ) { 
                        if(artikal === data.id_artikla){  
                            firstInput[i].status = "SAVED";  
                        } else { 
                            firstInput[i].status = "SAVE_ME";
                        } 
                     }); 
                i++;
            });

Does anyone have a solution to achieve the desired output with pure vanilla JS? - Note: the list is over 100 indexes long. Speed is crucial.

Answer №1

To optimize performance when dealing with large lists, it's best to avoid using nested loops that compare each item in one list with every item in another list. This approach would lead to O(n^2) comparisons.

Instead of nested loops, a more efficient method is to convert the second list, secondList, into a data structure that enables quick lookup by ID:

const articleSaved = {};
for (const item of secondInput) {
    articleSaved[item.id_artikla] = true;
}
for (const item of firstInput) {
    item.status = articleSaved[item.id] ? 'SAVED' : 'SAVE_ME';
}

It's important to note that this code modifies the existing objects. If you prefer to create new objects instead, you can utilize the following:

const result = firstInput.map(item => Object.assign({}, item, {status: saved[item.id] ? 'SAVED' : 'SAVE_ME'}));

Answer №2

If you haven't already, consider implementing Array.prototype.find(). This method could potentially solve your issue. Take a look at the details here

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

Web server experiencing issues with loading scripts and CSS files

After successfully building my project using CodeIgniter on localhost, I encountered an issue when trying to run it on a webhost. The site was functional but the design elements such as scripts and stylesheets were not loading properly. Before uploading t ...

a service that utilizes $http to communicate with controllers

My situation involves multiple controllers that rely on my custom service which uses $http. To tackle this issue, I implemented the following solution: .service('getDB', function($http){ return { fn: function(){ return $http({ ...

Using PHP to access a property using json_decode

Hello, I am attempting to access certain properties using json_decode, but I am encountering issues. Specifically, I am interested in retrieving the values for userRating and pressRating properties. $result_json = json_decode($result, true); echo $result_j ...

jQuery Slider not appearing on the page

I am attempting to incorporate the Basic jQuery Slider into my website. Below is the code I have used: For HTML file: <div id="slides"> <ul class="bjqs"> <li><a href="somelink"><img src="someim ...

What is the best way to pass the JWT token to the subsequent page once a user has successfully logged in on Next.js?

Introduction I am currently working on a login application using Nextjs for the frontend and Spring Boot for the backend. Issue The problem I am facing is that after successfully logging in from the frontend, which calls the /authenticate login API devel ...

I am currently facing an issue with retrieving the class value that is being generated by PHP code

I am currently facing an issue with jQuery and PHP. Whenever I attempt to target the click event on the class ".id_annonce" in the dynamically generated PHP code, it doesn't retrieve the exact value of what I clicked. Instead, it always gives me a fi ...

React - verifying properties

Here's a question that I've been pondering. In many situations, we find ourselves needing to check if props are undefined. But what about nested props? For example, let's say we have: this.props.data.income.data1.value.chartData and we wa ...

Navigate back to the previous route within the Vue router hierarchy

In my Vue application, I have a Settings page with child routes such as settings/user, settings/addUser, etc. I am looking to implement a back button that when pressed, takes the user back to the specific page they visited within the Settings section. Usin ...

What is the best way to convert Arabic language HTML into a PDF document on the client side?

Utilizing jsPDF and vue js, I successfully implemented a feature to export PDFs. However, I encountered an issue with Arabic characters not displaying properly. Can anyone provide assistance in resolving this problem? ...

Encountering difficulty in implementing two modals simultaneously on a single web page while utilizing the useDisclosure() hook in Ch

ChakraUI provides a custom hook called useDisclosure() which gives you access to isOpen, onClose , onOpen. const { isOpen, onOpen, onClose } = useDisclosure() You can use the onOpen function as an onClick handler for a button to open a modal. <Modal ...

What is the best way to show distinct items and their frequencies from an array of objects in Vue.js/JavaScript?

I have been developing an inventory management application using Vuejs, and I am facing a JavaScript-related challenge in my project. The issue revolves around handling data that includes user information retrieved from a form, as well as static categories ...

How does combineReducers in Redux determine which specific portion of the application state to send to the reducer?

While going through the Redux basics tutorial, I found myself a bit confused about how the code snippet below determines which part of the application state should be passed to each reducer mentioned in the combineReducers function. Does it simply rely o ...

What is the best way to deduct pixels from numbers using JavaScript?

Currently, I am attempting to adjust the height of the footer based on the height of another div element. My approach involves utilizing the .css("height") function. However, I am encountering difficulty as the function does not seem to return the value i ...

Show a variety of logos on the website based on the current date

I've been experimenting with displaying a unique logo on my website based on the current date (for example, showing a Christmas-themed logo during December). Here's what I have so far: <img class="logo" id="global_logo" sty ...

Utilize the power of AJAX for efficiently sorting search results retrieved from MySQL

I'm in the process of designing a flight search page. The initial page contains a form, and when the submit button is clicked, the search results are displayed on the second page. Here's the link to the first page: To test it out, please follow ...

MVC4: Exploring the Strategy for Handling Nested Ajax Requests

Creating a form in a web application, I implemented filtering data based on user selection using AJAX to retrieve JSON nested data from BankPlans table. However, I encountered an issue when attempting to fetch all required documents for each bankID from an ...

Obtaining Master-Detail table data via WebAPI

I have a scenario where I am working with a database that consists of two tables linked by a foreign key relationship, following the classic master-detail structure. My goal is to retrieve all the data from these tables using ASP.NET MVC WebAPI calls from ...

Manipulate Angular tabs by utilizing dropdown selection

In my latest project, I have developed a tab component that allows users to add multiple tabs. Each tab contains specific information that is displayed when the tab header is clicked. So far, this functionality is working perfectly without any issues. Now ...

Tips for retrieving element height using Vue.js

I am attempting to retrieve the offsetHeight of an element but I keep getting undefined. When I use this code, it returns an HTML collection and everything works correctly: document.getElementsByClassName("plyr--full-ui"); https://i.sstatic.net/xurBa.pn ...

Updating JSON files with jq in a bash script

Struggling with updating a value in a JSON file using the jq command. Can anyone help? Error: [jenkins@devops-dev-02 New]$ jq 'map(if .Tags[11].Key == "Period" then .Tags[11].Value = "Weekly" else . end)' create_snapshot.json ...