Merging object keys and values from JSON arrays based on their keys, using JavaScript

Is there a way to merge object keys' values from JSON arrays based on their key?

json1 = [
          {key:'xyz', value:['a','b']},
          {key:'pqrs', value:['x','y']}
        ]

json2 = [
          {key:'xyz', value:['c','b']},
          {key:'pqrs', value:['e','f']}
        ]

I am looking for a solution in JavaScript to combine the object keys' values as shown below

 json3 = [
              {key:'xyz', value:['a','b','c']},
              {key:'pqrs', value:['x','y','e','f']}
            ]

Essentially, I want to merge unique values of objects from JSON arrays by their key.

Answer №1

One way to manipulate data is by utilizing the forEach() loop for adding elements to an array and using a Set to eliminate duplicate values in objects.

var json1 = [{key:'xyz', value:['a','b']},{key:'pqrs', value:['x','y']}]
var json2 = [{key:'xyz', value:['c','b']},{key:'pqrs', value:['e','f']}]

var result = []
json1.concat(json2).forEach(function(e) {
  if(!this[e.key]) this[e.key] = e, result.push(this[e.key])
  else this[e.key].value = [...new Set(this[e.key].value.concat(e.value))]
}, {})

console.log(result)

Answer №2

function mergeJSON(json1, json2) {
var result = []
  for (let i = json1.length; i--;) {
  json2Obj = json2.find(item => item.key === json1[i].key)
  result.push({
  key: json1[i].key,
  value: json1[i].value.concat(
  json2Obj ? json2Obj.value : []
  )
  })
  }
  return result
}

json1 = [
  { key: 'abc', value: ['l', 'm'] },
  { key: 'efgh', value: ['p', 'q'] }
]

json2 = [
  { key: 'abc', value: ['r', 'm'] },
  { key: 'efgh', value: ['u', 'v'] }
]


console.log(mergeJSON(json1, json2))

Answer №3

When you combine arrays together, it is known as a union in the realm of mathematics, specifically set theory (for more information, check out this link).

If you want to learn more about how to implement a union in JavaScript with arrays, take a look at this discussion on Stack Overflow 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

The v-html command displays unprocessed HTML code on the webpage

This is a visual representation of my component: <template> <div v-html="someHtml"></div> </template> <script> export default { name: "test", props: { someHtml: String, }, } </script&g ...

Is there a way to eliminate blank elements in a JSON array on iOS?

Is there a way to filter out empty objects from a JSON array on iOS? [ {"latitude":"", "longtitude":""}, {"latitude":"13.0856", "longtitude":"70.2423"}, {"latitude":"13.0856", "longtitude":"70.2423"} ] The first set of latitu ...

Can you explain the meaning of the ?. operator in JavaScript?

While using react-hook-form, I encountered the ?. operator. Can you explain its meaning? Here's an example of how it works: <span>{errors?.name?.message}</span> The errors variable is obtained from useForm() by destructuring, as shown bel ...

JOLT specification for transforming a deeply nested JSON into a flattened JSON format

Seeking assistance on the Jolt specification needed to convert a nested JSON structure into a denormalized JSON. Input: { header : company: "ABC", ip: 10.3.2.4, network : [ {url:"http://abc.in", "latency":2000}, {url:"http://xzy.au", "l ...

Utilizing jQuery for easy drag-and-drop functionality in web development

I have two lists which are currently using jQuery for functionality. An example can be found here. I need the same basic functionality but with some modifications: Instead of just getting all sortable items by clicking "Get items," I want to be able to dr ...

Is it possible to trigger an event each time an Ajax request is made within AngularJS?

I am looking for a way to automatically display a spinner with a dark overlay every time a call is made to the backend. While I know I can manually implement this by triggering the spinner before each call, I prefer a solution that does not require addit ...

What is the best way to combine these two arrays in order to generate the desired JSON structure in a React

Is there a way to transform two arrays like these: const age = [31,53,62] const names = ['john', 'sam', 'kathy'] Into the structure shown below: const data = { "children": [ { "id": 1, "name": "john", "age ...

Tips for modifying the style of a component within node_modules using its individual vue <style> sections

I am trying to modify the CSS file within the multiselect package, but I don't want to make changes directly in the node_modules folder. Instead, I want to add my custom styles between the style tags of my Vue page. Specifically, I am attempting to ad ...

Ways to attach an item using its lower point instead of its upper coordinate

I am currently working on a poker table project using React. As of now, I have player components that need to be strategically positioned around the table. https://i.sstatic.net/gX9Ij.png One challenge I'm facing is that when the screen attribute ch ...

Java applet: keep an eye on incoming HTTP requests

I'm currently working on developing a Java applet and I would like to establish a connection to a webpage. Afterwards, this webpage will undergo several GET requests towards an external server. Could someone provide details on how I can view the speci ...

What is the reason behind not being able to utilize addEventListener on a variable that has been selected through DOM's getElementsByClassName method?

btn = document.getElementsByClassName('btn'); value = document.getElementById('value'); let counter = 0; btn[2].addEventListener('click', function() { if (btn[2].classList.contains('decrease')) counter -= 1; if ...

How can I troubleshoot the issue of the WCF Service not returning results even though the stored procedure is successful?

Recently, I developed a WCF service using C# which acts as the backend for a Webapp. The purpose of this WCF is to interact with stored procedures in a SQL database and return the queried data in JSON format for display on the WebApp. However, I've en ...

Seeking help with a Javascript regex inquiry

I am currently utilizing JavaScript regex for the following task: I have gathered the HTML content from a page and stored it within a string. Now, I aim to identify all URLs present on this page. For instance, if the document includes-- <script src = ...

Concealing the URL Once Links are Accessed

I have a Movie / TV Shows Streaming website and recently I've noticed visitors from other similar sites are coming to my site and copying my links. Is there a way to hide the links in the address bar to make it more difficult for them to access my con ...

Troubleshooting 404 errors on Firebase hosting with dynamic routes

My next.js app is deployed on firebase. The app has been deployed and in use for some time now. I created a dynamic route page Redeployed the app While I could access the dynamic page via a router, I encountered a 404 page not found error upon refreshing ...

Is the behavior of String.replace with / and different in Node.js compared to Chrome?

Creating a router in Node.js involves mapping URIs to actions, which requires an easily configurable list of URIs and regular expressions to match against the request URI. This process may seem familiar if you have experience with PHP. To test this functi ...

Discovering methods to access properties from another function

Can I access the value of variable w from another function? <script type="text/javascript"> var first = { myFirst: function(){ var w= 90; var q=12; }} var second= { mySecond: function(){ first.myFirst.w }} </script> ...

"Trouble with MongoDB aggregate query: Adding a new stage to pipeline leads to zero

Running an aggregate query through PyMongo and encountering some unexpected results. The MongoDB aggregate query looks like this: [{ $match: { syscode: { $in: [598.0] }, date: { $gte: newDate(1509487200 ...

Sending Laravel ajax request with ID before selection of options

I am attempting to create a search function using 4 dropdown menus, where each subsequent menu loads data based on the item selected in the previous dropdown. Approach field = Dropdown option Field 1: select A Field 2: options B, C (Select B) Field 3: ...

Steps for assigning distinct identifiers to information entered through an input form

I have a question that I just can't seem to figure out: So, I have this input form: <form @submit.prevent="customSubmit"> <label>Name</label> <input type="text" v-model="newUser.name" id=&quo ...