Combining two JSON arrays by finding the elements that are common to both and those that are

I've been attempting to combine two JSON arrays with objects as elements. You can check out this plunkr file for both JSON files. I have successfully retrieved the expected final outcome array id, but I'm unsure how to structure the expected JSON as shown below. I am using underscore js for this task.

Note: If an object exists in newJson and not in currentJson, after merging, it will be in the 'inactive' state by default.

I'm not certain if I'm taking the correct approach. This is what I've tried:

var newJsonID = _.pluck(newJson, 'id');
var currentJsonID =  _.pluck(currentJson, 'id');
var union = _.union(newJsonID, currentJsonID);
var intersection = _.intersection(currentJsonID, newJsonID);
var final = _.difference(union, _.difference( currentJsonID, intersection);

Expected Final Outcome:

   [
    {
        "id": "12",
        "property1Name": "1"
        "status": "inactive"
    },
    {
        "id": "11",
        "property1Name": "1"
        "status": "inactive"
    },
    {
        "id": "10",
        "property1Name": "1"
        "status": "inactive"
    },
    {
        "id": "9",
        "property1Name": "1"
        "status": "active"
    }
]

Answer №1

This innovative solution utilizes plain Javascript, incorporating two loops and a hash table for efficient lookup.

function mergeArrays(newArray, currentArray) {
    var hashTable = Object.create(null);
    currentArray.forEach(function (element) {
        hashTable[element.id] = element.status;
    });
    newArray.forEach(function (element) {
        element.status = hashTable[element.id] || 'inactive';
    });
}

var newJsonData = [{ "id": "12", "property1Name": "1" }, { "id": "11", "property1Name": "1" }, { "id": "10", "property1Name": "1" }, { "id": "9", "property1Name": "1" }],
    currentJsonData = [{ "id": "10", "property1Name": "1", "status": "inactive" }, { "id": "9", "property1Name": "1", "status": "active" }, { "id": "8", "property1Name": "1", "status": "active" }, { "id": "7", "property1Name": "1", "status": "inactive" }];
   
mergeArrays(newJsonData, currentJsonData);
document.write('<pre>' + JSON.stringify(newJsonData, 0, 4) + '</pre>');

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

The Bootstrap form validation is preventing the Ajax request from functioning properly

Having successfully implemented a form with Bootstrap validation, I encountered an issue where the AJAX Post method fails to execute after validation. The catch clause does not capture any errors and only the ajax portion of the code doesn't run. Belo ...

What is the best way to save the values of a particular attribute from several documents?

I have a challenge where I need to extract the ObjectID values from multiple documents stored in a single collection and store them in a single array. I'm currently stuck on how to achieve this task. Below is what I've tried so far: app.get("/se ...

Error: Unexpected token '<' encountered in Ajax request with status code 200

While attempting to run an ajax request, I keep encountering the error message 'Syntax Error: unexpected token <' along with a xhr.status of 200. Strangely, I am able to successfully email the variable passed from the JavaScript file to the PH ...

The MUI Slider Component is causing the entire page to go blank

I have implemented the Range Slider component: import React from 'react'; import Box from '@mui/material/Box'; import Slider from '@mui/material/Slider'; function valuetext(value) { return `${value}°C`; } export default f ...

React - Image Uploader exclusively accepts images with transparent backgrounds

I need to verify if an image has a transparent background and reject it if it does, but accept it if it doesn't. However, I am facing an issue where the hasAlpha function is not triggering an 'error' alert when the image contains a backgroun ...

How can the last child in ng-repeat in AngularJs be hidden?

I have a ng-repeat loop in my code that displays different providers. <span ng-repeat="provide in user.profiles"> <span ng-switch on="provide.provider"> <span ng-switch-when="google" class="color-google">GOOGLE</span> & ...

After successfully building with Vite, an error occurs stating "TypeError: can't convert undefined to object." However, during development with Vite, everything functions flawlessly

Currently, I am utilizing Vite in conjunction with React and Typescript for my project. Interestingly, when I execute 'vite dev', the live version of the website works flawlessly without any errors showing up on the console. However, things take ...

Retrieving JSON data using cURL with cookie results in the message: "Cookie value ÿÿ)»L"

I am currently attempting to extract the data from this particular JSON file: Below is the snippet of code I am using: $url = "http://steamcommunity.com/market/pricehistory/?country=DE&currency=3&appid=730&market_hash_name=Chroma%20Case"; $c ...

`Finding the nodejs API route for displaying images from a database`

How can I successfully display an image from the database without getting a string of question marks instead? Click here to see the issue >>> When attempting to directly call the API using the provided link, the following result is returned: {&qu ...

Enhance user experience by implementing jQuery autocomplete feature to efficiently populate multiple fields using JSON data from a single

I'm currently working on integrating the jQuery autocomplete plugin with a local JSON variable as the input. My goal is to have the adjacent address fields populate automatically once the user selects an option from the autocomplete list. Below is th ...

Typescript inheritance results in an undefined value being returned

I am trying to understand the code below, as I am confused about its functionality. In languages like C# or Java, using the base or super keyword usually returns values, whereas in TypeScript, I am receiving "undefined". However, when I switch from using " ...

In need of clarification on the topic of promises and async/await

I have been utilizing Promises and async/await in my code, and it seems like they are quite similar. Typically, I would wrap my promise and return it as needed. function someFetchThatTakesTime(){ // Converting the request into a Promise. return new ...

Vanilla JavaScript - Conceal all remaining div elements

I have a situation where multiple divs are only visible after clicking a link. How can I ensure that when one div is clicked, all others are closed so that only the clicked one remains visible? Currently, I am using the following JavaScript: functio ...

String values should determine whether a checkbox is checked or not

When retrieving data from LocalStorage, my code looks like this: angular.module('madMeApp').controller('campaignInDetails', function($scope) { var campaignToShow = JSON.parse(localStorage.getItem("CampaignDetails")); $scope.selecte ...

Look for identical values within a nested array

My data consists of a nested array where each element has a property called name, which can only be either A or B. I need to compare all elements and determine if they are all either A or B. Here is an example of the input: [ { "arr": { "teach ...

Avoid the occurrence of $("html").ajaxError() by ensuring it is not present in any of the $.ajax

$("html").ajaxError(function (event, jqXHR, ajaxSettings, thrownError){ //display appropriate message depending on the error. }); Furthermore, I am transmitting JavaScript errors to the server via $.ajax() within the catch block and using the window.one ...

Is it feasible to lower AWS data transfer expenses by transitioning from HTTP APIs to gRPC services?

My web service handles a large volume of traffic, sometimes reaching millions per minute. It is hosted on AWS EC2 behind an ELB and utilizes HTTP APIs, resulting in a significant portion of my AWS bill going towards Data Transfer fees. The Data Transfer Ou ...

Tips on iterating through fields within an Express request to construct form data?

I am currently working with a piece of code which contains the following: res.send(` fd.append('policy', '${presigned.fields.Policy}'); fd.append('X-Amz-Signature', "${presigned.fields['X-Amz-Signature&ap ...

Does MongoDB have an equivalent to prepared statements in PHP for enhancing security measures?

As I delve into learning mongodb, a pressing question arises. Does mongodb have security features similar to those found in PHP? In PHP, one could utilize the following code: $stmt = $this->conn->prepare("UPDATE news SET shown = shown+1 WHERE ne ...

Slideshow: I hope the Radio Button triggers the appearance of the next item in the rotation

I need to implement a carousel that displays the next item (Id="item2") when a specific radio button (Id="item1") is selected by default and another radio button (Id="item2") is pressed. Ideally, I would like to achieve this ...