"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

Issue with importing in VueJS/TypeScript when using gRPC-Web

I have developed a straightforward VueJS application and am currently grappling with incorporating an example for file upload functionality. The proto file I am utilizing is as follows: syntax = "proto3"; message File { bytes content = 1; } ...

Error encountered while compiling NextJS: Unexpected use of single quotation mark in jsx-quotes

I can't seem to compile my NextJs 13 app without encountering errors. Take a look at my shortened eslintrc.js file below: module.exports = { env: { browser: true, es2021: true, }, extends: [ 'plugin:react/recommended', ...

What could be the reason for the React component not re-rendering even after its prop has been updated?

One of the challenges I'm facing with an application I'm currently working on is a re-render issue. To simplify, let's say we have two components - DisplayElement1 and DisplayElement2. In this scenario, DisplayElement2 iterates through a ba ...

Python Elastic Reindex: issue with field [source] parsing encountered

I have been attempting to reindex an index using a Python function like this: resp = client.reindex( body={ "source": { "remote": {"host": "url_name:9200","username": &qu ...

Using the React key attribute for components without distinct identifiers

When dealing with a situation where users need to provide a list of timeframes, it can be tricky to generate a unique key for each component in React. Simply using the index of the array is not sufficient, as items can be removed from the middle of the lis ...

What reasons underlie the existence of various methods for importing Modules in JavaScript?

I'm confused about the distinctions when it comes to importing a JavaScript module in various ways such as: CommonJS ES5 ES6 NodeJS Typescript What is the reason for having multiple methods of importing JavaScript modules? Is the concept of a "modu ...

What does the "Undefined" group label mean in Vue-Multiselect?

I recently started learning Vue and have revamped this code based on information from different tutorials. However, I am encountering an issue with the group name showing as "Undefined" here. .html: <multiselect v-model="value" :options="op ...

Converting JSON data to an array - dealing with both single and double quotes

I have a large JSON code consisting of 2,801,278 characters. I am trying to create an array from this JSON code in my PHP script, but I am facing issues due to the presence of quotes and double quotes which are causing errors. Here is a simple example that ...

Unable to retrieve a return value from an asynchronous waterfall function within a node module

A custom node module that utilizes async waterfall is working properly when run independently, but the AJAX callback does not receive the return value. //Node module var boilerplateFn = function(params){ async.waterfall([ function(callback){ ...

How can I create a regex pattern that will exclude characters within parentheses?

While working on some regex, I encountered a bug: The scenario is as follows: I have this string - for example "+1/(1/10)+(1/30)+1/50" and I applied the regex /\+.[^\+]*/g to it, which worked perfectly giving me ['+1/(1/10)&apos ...

The error was thrown at line 800 in the loader.js file of the internal modules

When I ran yarn install in my project folder, I encountered the following error: internal/modules/cjs/loader.js:800 throw err; ^ Error: Cannot find module 'ts-node/register' Require stack: - internal/preload ?[90m at Function.Module._resolveF ...

InnerHTML syntax for creating the button in the cell is not functioning properly with the HTML onclick event

I'm facing an issue with my code where I am trying to insert a button into a table cell. The button has an action assigned to it using the onclick attribute. However, no matter how I try to use single quotes with or without backslashes in the syntax o ...

In Internet Explorer 10, it is not possible to access the document.links using the link's id; it can only be accessed using the

Why does the following code work in FireFox 23.0.1 and Chrome 29, but not in IE 10? <!DOCTYPE html> <html> <head> <title></title> <script type="text/javascript"> function loadFile1(){ a ...

Swap out a div identifier and reload the page without a full page refresh

I am interested in learning how to dynamically remove a div id upon button click and then add it back with another button click to load the associated CSS. The goal is for the page to refresh asynchronously to reflect these changes. So far, I have successf ...

Is there a way to remove a row through fetch using onclick in reactjs?

I'm completely new to this and struggling with deleting a row using fetch. I've written some messy code and have no idea if it will even work. Please help, I feel so lost... renderItem(data, index) { return <tr key={index} > &l ...

What is the optimal method for storing extracted JSON data?

One question on my mind is how to effectively store JSON data. I have a JSON file that I parse using JSON Library and now I have the data from the file. However, I want to be able to store this data for future use. I'm seeking advice on the best way ...

Attempting to create a Next.js 13 application, but struggling with using the client-side functionality

Exploring Next.js for the first time, I embarked on creating a simple application. Everything was going smoothly until I attempted to include a "use client" tag at the beginning of a component to utilize certain hooks. This resulted in the app breaking and ...

Conceal or reveal buttons using JavaScript

I am struggling with a function that is supposed to hide certain buttons and create a new button. When I click on the newly created button, it should make the previously hidden buttons visible again. However, the function does not seem to work properly. ...

monitoring checkbox status in vue?

When using Vue, I have created dynamic checkboxes that display as shown below: <li v-for="element in checklist" :key="element.id" class="block w-full p-1"> <div v-if="element.taskId == task" clas ...

Unusual behavior observed when filling a Spinner from a database source

I am facing an issue while trying to populate a spinner from a MySQL database using JSON. The data is successfully exported, but the app crashes when I click on the Spinner to show the dropdown menu. The JSON output from the database can be viewed here. ...