"Implement a function to append a new item to all JSON objects in an array if they share a common value with a different JSON object in the array using

Hi there, I'm new to Vue Js and I'm currently working on adding or merging new items in all JSON objects within an array that share the same value with another JSON object. I know how to push a new JSON object into an existing one, but I would really appreciate some advice on how to achieve this. Thank you in advance!

JSON 1 (Main)
[
  {
    name: "a",
    id: 2,
    price: 300
  },
  {
    name: "b",
    id: 3,
    price: 100
  },
  {
    name: "c",
    id: 4,
    price: 50
  }
]

JSON 2 (List)
[
  {
    color: "red",
    id: w2,
    uuid: "3"
  },
  {
    color: "blue",
    id: y2,
    uuid: "4"
  },
  {
    color: "pink",
    id: xf,
    uuid: "3"
  },
  {
    color: "black",
    id: jf,
    uuid: "7"
  }
]

If the UUID of JSON 2 (List) matches the ID of JSON 1 (Main), I need to add another item in JSON 2 (List) inside an object named after the value of 'name' from JSON 1(Main), and remove any JSON objects in JSON 2 (List) whose UUID does not match any IDs in JSON 1 (Main). Here's an example of the expected output:


{
    color: "black",
    id: jf,
    uuid: "7"
} //will be removed

Expected Output 
[
  {
    name: "b",
    color: "red",
    id: w2,
    uuid: "3"
  },
  {
    name: "c",
    color: "blue",
    id: y2,
    uuid: "4"
  },
  {
    name: "b",
    color: "pink",
    id: xf,
    uuid: "3"
  }
]

Answer №1

If you want to extract a list of matching items, consider utilizing Array.reduce. This method offers versatile capabilities for array manipulation and can generate a variety of outputs.

By iterating through the json2 array and searching for matches in the json1 array (using Array.find), we can identify corresponding items based on uuid = id. Subsequently, the merged object is added to the returning array;

let json1 = [ { name: "apple", id: 2, price: 300 }, { name: "banana", id: 3, price: 100 }, { name: "cherry", id: 4, price: 50 } ];

let json2 = [ { color: "red", id: 'w2', uuid: "3" }, { color: "blue", id: 'y2', uuid: "4" }, { color: "pink", id: 'xf', uuid: "3" }, { color: "black", id: 'jf', uuid: "7" } ];

let result = json2.reduce((returnArray, item) => {
    // Locate a match in the json1 array.
    let match = json1.find(el => el.id == item.uuid);
    if (match) {
        // Upon finding a match, create a merged object combining properties from both arrays.
        returnArray.push({ ...item, name: match.name});
    }
    return returnArray;
}, []);

console.log("Result:", 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

Encountering a JavaScript Error: "e is null" while utilizing assert for checking JavaScript alert text

I encountered a javascript alert in my program that I was able to interact with by reading the text and clicking on the buttons. However, when I tried to verify the alert text using assertequals function, I faced an error. Here is the code snippet: String ...

The intricacies of the Jscript ReadLine() function

I am trying to figure out how to read the complete content of a .txt file using JavaScript. I know that ReadLine() can be used to read a specific line from a file, but I need a method that will allow me to read the entire contents of the file. I have searc ...

Reduce the combined character value of the title and excerpt by trimming the excess characters

I am seeking a solution to trim the total character count of a post title and excerpt combined. Currently, I can individually adjust the excerpt through theme settings and the post title using JavaScript. However, due to varying title lengths, the height ...

Next.js application shows 404 errors when trying to access assets within the public directory

I've been struggling to display the favicon for my site (which uses next.js). Despite going through numerous Stack Overflow posts and tutorials, I'm feeling increasingly frustrated. The structure of my project, particularly the public directory, ...

Javascript: Accessing a shared variable within the class

Embarking on my JavaScript programming journey filled me with optimism, but today I encountered a challenge that has left me stumped. Within my tutorial project, there exists a class named Model which contains both private and public variables. Of particu ...

Ways to extract only numbers from a string

I have encountered a frustrating issue in VueJS: I am receiving an object with the following structure: { "description": "this is our List.\n Our Service includes:\n-1 something\n-2 something else\n and another thing\n"}` My dile ...

What could be causing the issue of Vuejs 3.3 defineModel consistently returning undefined?

I am currently working with Nuxt version 3.5.1 and Vuejs version 3.3, however, I am encountering an issue where the defineModel macro always returns undefined. I am unsure why this is happening? <template> <input v-model="count"& ...

Retrieve only the names of keys from a JSON object presented in array form using Node.js

How can I retrieve JSON data key names and store them in an array using nodejs? I attempted the following code, but it returned an object instead of an array. I need the key names in an array format so that I can save them in a variable. const jsondata = ...

Unusual conduct when employing basic directive for validation messages

Within my code, I have implemented the following directive: App.directive("validateMsgFor", function(){ return{ templateUrl : "view/templates/validateMsgFor.html", restrict: "E", scope: { field : "=" } ...

Using a variable in a Joomla module to create a JavaScript object with PHP

I am currently developing a Joomla module that features a progress bar utilizing the ProgressBar.js plugin. Since this module is designed to load multiple objects on a single page, hardcoding the IDs of these objects is not feasible. To address this, I uti ...

Rendering data in React using the array indexRendering data in React

I'm encountering an issue in React JS where I need to display all data from a REST API with a numeric index. REST API: [ { "id": "1", "start_date": "2020-05-08 09:45:00", "end_date": "2020-05-08 10:00:00", "full_name": "mirza", "cust_full_name": "fu ...

Is there a way to showcase all the information in products while also organizing it in the same manner that I have?

I am looking to sort prices while displaying all the properties of products at the same time. DATA INPUT: const products = [ { "index": 0, "isSale": true, "isExclusive": false, "price": "Rs.2000", "productImage": "product-1.jpg", ...

Is there a way to view the contents of a file uploaded from <input type="file" /> without the need to send it to a server?

Having trouble uploading a JSON file from my local disk to Chrome storage. Whenever I use the <input type="file"> tag and useRef on the current value, it only returns the filename prefixed with 'C:\fakepath...' ImportExport Component: ...

Guide on transforming JSON into a basic 2D Array

Here is an example of a JSONObject structure: [{"key1":1,"key2":"yyy","key3":"4"..........}, {"key1":2,"key2":"xxx","key3":"5"...........}, {"key1":3,"key2":"zzz","key3":"6"...........}] I am looking to convert this JSONObject into a simplified 2D arra ...

Obtain JSON data instead of XML data from a web service through Ajax with the option 'contentType' set to 'false'

Upon making an AJAX call to send an image file to one of my web service (.asmx) methods, I encountered a problem where the web service returns XML instead of JSON. This issue arose because I needed to set the contentType to false, in order to successfully ...

I keep encountering an attach() error every time I try to close a modal that contains a vee-validated form

Every time I try to close a bootstrap modal (using bootstrap-vue) that includes a vee-validated "update" form with vue.js, I encounter the following error: main.js:477686 Uncaught (in promise) Error: [vee-validate] Validating a non-existent field: "#35". ...

I'm confused about what I did wrong with Node.js. The server.js is up and running, but I'm unable to view the

I have made some progress so far and I am currently running this code on Putty. var http = require('http'); var fs = require('fs'); const PORT = 8080; http.createServer(function(request, response) { var url = request.url; switc ...

Using jQuery Datatables: Storing the received JSON data into a variable

I have incorporated 2 plugins for my project: Datatables (used for pagination) Defiant.js (providing JSON search capability) Describing my issue along with the code snippet... $(document).ready(function() { var myjson; //Initializing Datatable ...

What are the best ways to utilize getElementById in React?

As a beginner in React, I am attempting to create an auto text animation for my project. While I have successfully implemented it in VanillaJS, I am facing challenges with doing the same in React. import React, { Component } from 'react' class A ...

"Enjoying a table header that scrolls freely with autoscroll feature

Resolved - http://jsfiddle.net/CrSpu/11704/ I'm facing an issue with a table that has autoscroll functionality. I am looking to freeze the header of the table when automatic scrolling occurs, or you can test it out using my code pen. I'm uncer ...