"Comparing JSON objects can be done by checking if their IDs match, and if they do, assigning the value to another object

I am working with two sets of data

var JSON_Categories = '[{ "id" : "1", "text" : "Category A"}, { "id" : 2, "text" : "Category B" }]';
var JSON_Article = '[{ "id" : "1", "text" : "Article text A"}, { "id" : 3, "text" : "Article B"}]';
var categories = JSON.parse(JSON_Categories);
var article = JSON.parse(JSON_Article);

In the scenario where the id matches in both JSON objects, I need to pair the category text value with the corresponding article text value.

I attempted a solution but I know it's not ideal. Can anyone provide assistance?

var categoryValue = new Object();
categories.forEach(function(category) {
articles.forEach(article => {
    if (category.id === article.id) {
        categoryValue.id = category.id;
        categoryValue.text = article.text;
    } else {
        categoryValue.id = category.id;
        categoryValue.text = category.text;
    }
});
});

console.log('categoryValue', categoryValue);

       

Answer №1

If you want to map it and then use find to locate the Object from the second array:

var JSON_Categories = JSON.parse('[{ "id" : "1", "text" : "Category A"}, { "id" : 2, "text" : "Category B" }]');
var JSON_Article = JSON.parse('[{ "id" : "1", "text" : "Article text A"}, { "id" : 3, "text" : "Article B"}]');

var result = JSON_Categories.map(({id, text})=>({id, text:JSON_Article.find(k=>k.id==id)?.text || text}));

console.log(result);

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

Effective ways to transfer data between services and controllers

Is there a way to pass values from services to controllers effectively? Despite researching on stackoverflow, I haven't found a solution that addresses my issue. My goal is to access google spreadsheets using tabletop.js. Interestingly, when I log val ...

How to manually resolve a type by its string or name in Angular 2

I'm facing a challenge. Is it possible to resolve a component manually with just its name known? Let's say I have a string variable that holds the name of a component, like "UserService". I've been exploring Injector and came across method ...

The act of updating JQuery is causing my javascript code to malfunction completely

I've been attempting to update my jQuery library from version 1.3.2 (compressed) to jquery-1.10.2 (compressed) along with jquery-migrate-1.2.1 (compressed). However, after making this switch, none of the javascript pages on my website seem to be funct ...

What could be causing the .text method to not retrieve text even when it is present?

Currently experimenting with web scraping using Selenium to extract the color of a particular dress. Despite finding the text content under the 'screen-reader-text' class when inspecting the website, my attempts at fetching it result in an empty ...

Why is my jQuery SlideReveal not displaying on page load?

Can anyone provide some help? I am currently using the jquery.slidereveal.js plugin from ''. The plugin works well when manually clicking the trigger to open and close the menu. However, I would like it to default to its last state on page load, ...

``Using `fs.lstat` function to check the status of a symbolic link that points to

When using the fs.stat function in my Windows environment (x64) on a symlink pointing to a directory, I encounter an error. Contrastingly, when running the same code on Appveyor (ia32), the fs.stat function for a symlink pointing to a directory works with ...

Encountering an issue when attempting to downgrade React Native version from 0.51 to 0.45

My current project requires me to downgrade due to certain third-party packages not being updated for the latest version of react-native. Specifically, I am using Xcode 9.0. Despite my efforts to downgrade the react-native version, I encountered the follo ...

Verifying the presence of an image via its URL may not be functional across all browsers

Hey folks, I'm working on a project that involves displaying an image along with other fields in a loop where the image source changes with each iteration. I also need to check if the image exists and set a default source if it doesn't. The code ...

Chat lines in Chrome displaying double entries - troubleshooting needed

I developed a chat plugin for my website with a simple HTML structure: <div id="div_chat"> <ul id="ul_chat"> </ul> </div> <div id="div_inputchatline"> <input type="text" id="input_chatline" name="input_chatline" val ...

Angular efficient approach to changing object properties

When working on creating or updating records, I encounter a problem with the length and cleanliness of my code. The dealTypeValues object varies based on the dealDispositionType (buyout or sale), resulting in lengthy and messy code. Does anyone have sugge ...

Utilize NestJS to consume EventPattern exclusively when the header variable matches a specific value

I've been working on a NestJS project where I'm using a Kafka server to emit events and NestJS to consume them. My goal is to create a consumer with the topic my-topic that is triggered only when a specific value is present in the header variable ...

Unable to send a POST request to http://localhost:5000/api/createuser

During my journey through a MERN stack project tutorial on YouTube, I've come across a roadblock in the middle of my progress. The issue at hand involves the incorporation of user registration, which is a recent addition to my project. Utilizing Thund ...

Click on a link to navigate to a new page using the useNavigate hook in

I have successfully implemented navigation using the useNavigate hook, but I am wondering if there is a way to open the URL in a new tab instead of the current one. Is this achievable? Here's my code: import { useNavigate } from "react-router-do ...

I desire a smooth fade-in transition for the background image when the addClass function is

If the background color is set to header-fixed-position, the color will fade in. However, if the background is an image, the image will not fade in. Apologies for my lack of proficiency in English. Please refer to the sample code below. Try removing the c ...

Exploring front-end AJAX functionality within a WordPress plugin

As a newcomer to WordPress development, I have been working on writing an AJAX request within a WordPress plugin. To test this functionality, I initially sent the request to an external non-WP server where it worked without any issues. Following the guidel ...

What could be causing the content in my select box to change only when additional select boxes are introduced?

When working with a form in next.js and using select boxes from material UI, I encountered an issue. The number of select boxes should change based on user input, but when I modify the value inside a select box, the displayed text does not update until I a ...

I am trying to create a login application using angular and ionic, but I am facing an issue with accessing the $stateProvider routing for the login page through the <ion-nav-view> element

index.html Description: The index.html file is the main file containing all the view pages. It includes HTML code for setting up the structure of the application. <!DOCTYPE html> <html ng-app="loginApp"> <head> <meta charset="u ...

Arrange the JSON object according to the date value

I am working on a JavaScript project that involves objects. Object {HIDDEN ID: "06/03/2014", HIDDEN ID: "21/01/2014"} My goal is to create a new object where the dates are sorted in descending order. Here's an example of what I want: SortedObject ...

What is the best way to convert my JSON data to HTML using JavaScript?

My dilemma seems to be rooted in the use of backticks. Strangely, an error keeps popping up whenever I try to employ them in my IDE (Brackets). I attempted solutions by testing directly in my Browser and through NotePad++, but unfortunately, nothing seeme ...

Next.js is faced with a frustrating issue where images and videos are failing to display

I've been working on my Next.js 13 project with TypeScript, eslint, and Chakra UI, but I'm facing an issue with images and videos not displaying. Despite trying both the HTML <img> tag and importing Image from Chakra, the problem still per ...