Merge shared attributes into JSON with the help of JavaScript

I am looking to include a shared property in my JSON Object. Below is an example of the JSON object:

data = [
  {
    COUNTRY: 'USA',
    POPULATION: 300,
  },
  {
    COUNTRY: 'USA',
    POPULATION: 50,
  },
  {
    COUNTRY: 'Canada',
    POPULATION: 80,
  },
  {
    COUNTRY: 'USA',
    POPULATION: 60,
  },
  {
    COUNTRY: 'Mexico',
    POPULATION: 20,
  },
  {
    COUNTRY: 'Mexico',
    POPULATION: 40,
  },
  {
    COUNTRY: 'Canada',
    POPULATION: 10,
  },
];

The desired output is to add POPULATION field for recurring COUNTRY properties as shown below:

data = [
  {
    COUNTRY: 'USA',
    POPULATION: 410,
  },

  {
    COUNTRY: 'Canada',
    POPULATION: 90,
  },

  {
    COUNTRY: 'Mexico',
    POPULATION: 60,
  },
];

Answer №1

let data = [{
  "MKTUNITID": "India",
  "TOTCOUNT": 20,

}, {
  "MKTUNITID": "India",
  "TOTCOUNT": 4,

}, {
  "MKTUNITID": "China",
  "TOTCOUNT": 8,

}, {
  "MKTUNITID": "India",
  "TOTCOUNT": 6,

}, {
  "MKTUNITID": "Japan",
  "TOTCOUNT": 2,

}, {
  "MKTUNITID": "Japan",
  "TOTCOUNT": 4,
}, {
  "MKTUNITID": "China",
  "TOTCOUNT": 2,
}, ];

let resultData = data.reduce((result, {
  MKTUNITID,
  TOTCOUNT
}) => {
  result[MKTUNITID] = result[MKTUNITID] ? result[MKTUNITID] + TOTCOUNT : TOTCOUNT;
  return result;
}, {});

let finalResult = Object.keys(resultData).map(d => ({
  MKTUNITID: d,
  TOTCOUNT: resultData[d]
}));
console.log(finalResult)

Answer №2

To begin, gather all the distinct keys, then iterate through them to filter and reduce the total count of results.

const results=[ { "MKTUNITID": "India", "TOTCOUNT": 20,

}, { "MKTUNITID": "India", "TOTCOUNT": 4,

}, { "MKTUNITID": "China", "TOTCOUNT": 8,

}, { "MKTUNITID": "India", "TOTCOUNT": 6,

}, { "MKTUNITID": "Japan", "TOTCOUNT": 2,

}, { "MKTUNITID": "Japan", "TOTCOUNT": 4,

}, { "MKTUNITID": "China", "TOTCOUNT": 2,

},

];

console.log(
  [...new Set(results.map(obj => obj.MKTUNITID))]
    .map(key => ({
      MKTUNITID: key,
      TOTCOUNT: results.filter(obj => obj.MKTUNITID === key).reduce((a, b) => a + b.TOTCOUNT, 0)
    }))
);

Answer №3

To achieve this, you can utilize the Array.reduce method.

const data = [{
    MKTUNITID: 'India',
    TOTCOUNT: 20,
  },
  {
    MKTUNITID: 'India',
    TOTCOUNT: 4,
  },
  {
    MKTUNITID: 'China',
    TOTCOUNT: 8,
  },
  {
    MKTUNITID: 'India',
    TOTCOUNT: 6,
  },
  {
    MKTUNITID: 'Japan',
    TOTCOUNT: 2,
  },
  {
    MKTUNITID: 'Japan',
    TOTCOUNT: 4,
  },
  {
    MKTUNITID: 'China',
    TOTCOUNT: 2,
  },
];

const map = data.reduce((result, item) => {
  result[item.MKTUNITID] = result[item.MKTUNITID] || {
    MKTUNITID: item.MKTUNITID,
    TOTCOUNT: 0
  };

  result[item.MKTUNITID].TOTCOUNT += item.TOTCOUNT;
  return result;
}, {});

const finalResult = Object.values(map);

console.log(finalResult);

Answer №4

Utilizing the forEach method

results = [ { MKTUNITID: 'India', TOTCOUNT: 20, }, { MKTUNITID: 'India', TOTCOUNT: 4, }, { MKTUNITID: 'China', TOTCOUNT: 8, }, { MKTUNITID: 'India', TOTCOUNT: 6, }, { MKTUNITID: 'Japan', TOTCOUNT: 2, }, { MKTUNITID: 'Japan', TOTCOUNT: 4, }, { MKTUNITID: 'China', TOTCOUNT: 2, }, ];
g={}
results.forEach(obj=>!g[obj.MKTUNITID]?g[obj.MKTUNITID]=obj:g[obj.MKTUNITID]={MKTUNITID:obj.MKTUNITID,TOTCOUNT:obj.TOTCOUNT+g[obj.MKTUNITID].TOTCOUNT})
console.log(g)

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

Endless repetition occurs when invoking a function within a v-for loop

I've encountered an issue while trying to populate an array using a method, leading to redundant data and the following warning message: You may have an infinite update loop in a component render function. Below is the code snippet in question: ...

Good day extract a collection of articles

I am trying to parse out the date and full URL from articles. const cheerio = require('cheerio'); const request = require('request'); const resolveRelative = require('resolve-relative-url'); request('https://www.m ...

Why isn't my React image updating its source right away? What are some solutions to this issue?

I currently have a basic <img> tag with a specified src attribute. <img src={src} /> When I update the src attribute from, let's say /1.jpg to /2.jpg, there is a delay in loading the new image. React still displays the old image (/1.jpg) ...

Synchronizing information between different controllers using a service

After reading the discussion on this stackoverflow post, it seems like using services is the recommended way to transfer data between controllers. However, in my own testing on JSFiddle here, I encountered difficulties in detecting changes to my service w ...

Avoiding the use of numbers in v-if in Vue.js

My website features a left menu that displays different content based on the selected menu's ID. However, I currently have === 0 and === 1 in the v-if statement, and I'm looking for a way to avoid manually inputting these numbers. <template& ...

WSO2 PayloadFactory is delivering JSON data neatly packaged in a JSONObject

Currently, I am utilizing WSO2 API Manager 1.7.0 and experimenting with a simple payloadfactory to switch a call from a GET to a POST while passing in a json payload. In analyzing the log files, it seems that WSO2 is sending the json enveloped within {"js ...

Why does the header still show content-type as text/plain even after being set to application/json?

When using fetch() to send JSON data, my code looks like this: var data = { name: this.state.name, password: this.state.password } fetch('http://localhost:3001/register/paitent', { method: 'POST&a ...

What is the best way to structure JSON data for optimal display on Google Charts?

I've been diving deep into this code for hours on end, relentlessly searching Google for answers but coming up short... google.load('visualization', '1', {packages: ['corechart']}); google.setOnLoadCallback(drawVisuali ...

What is the process for exporting an NPM module for use without specifying the package name?

I am looking for a way to export an NPM module so that it can be used without specifying the package name. Traditionally, modules are exported like this: function hello(){ console.log("hello"); } module.exports.hello = hello; And then imported and ...

Navigate to an element with a specific ID using JavaScript

How can I implement scrolling to an element on a webpage using pure javascript in VueJS with Vuetify framework? I want to achieve the same functionality as <a href="#link"></a> but without using jQuery. My navigation structure is as follows: ...

Ensure that the div remains within the viewport

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Tit ...

Struggling to adjust the dimensions of a React Barcode to the specified width and height?

I've encountered an issue with resizing the React Barcode Image. I prefer all barcodes to have a width of 200px and a height of 100px. From what I understand, the width of the barcode will expand when the length value increases. Below is my current co ...

Looking to update the display of an array received in JSON format and then show it using ng-repeat?

Upon receiving a response from the backend, I am saving it in a variable called "allinfo" in my controller. The data received includes the name, date of birth, and hobby of a person. The hobby is an array that can contain any number of elements. In my vie ...

Using jQuery to add a checkbox to a list that is not ordered

My HTML structure includes an unordered list with nested lists. Here is a snippet of the code: <div id="checklist"> <ul> <li>On Page SEO <ul> <li>My work <i>And note.</i>< ...

experiencing issues with JSON parsing in Xcode

Having an issue with the following code: - (void)fetchedData:(NSData *)responseData { //parse out the json data NSError* error; NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error]; ...

Is your JQuery Gallery experiencing issues with the next button function?

I'm working on developing a simple gallery using JQuery. The main concept is to have all image files named x.png (where x is a number), and the program will then add a number to the current one, creating x+1.png and so forth. Here's the code I ...

Determining the most recent array within an array object in PHP

My goal is to extract data from a JSON object, transform it into an array of objects, and then determine the latest array within this structure based on a specific set of values. For example: // Array structure [ [response] => [ [0] => [ ...

Form a collection using multiple elements

I'm attempting to combine multiple arrays into a single array. For instance : array1= ['Joe','James','Carl','Angel','Jimmy',]; array2= ['22','11','29','43',&apo ...

Use a swipe gesture to move through the slideshow on a touchscreen device

I am currently working on a slideshow that allows users to navigate through images by clicking either the next or previous buttons. When a user clicks on one of these buttons, the next or previous image is loaded into the img src, as shown below. In addit ...

Issue when attempting to animate an SVG point using translateX transformation

I am attempting to create a basic animation using the translate X property on a section of my svg when hovering over the element. Here is the code I have so far: <html> <style> .big-dot:hover { transform: translateX(20px); animat ...