JavaScript - What is the best way to add the same object value into an array?

After spending a few hours trying to figure out how to manage JSON data structured like this:

[
  {
    "value": "Osteonecrosis",
    "Diagnosis_Code": "DIAG002",
    "NamaCategory": "Primary Category",
    "FK_Diagnosis_Content_ID": 2
  },
  {
    "value": "Malunion",
    "Diagnosis_Code": "DIAG002",
    "NamaCategory": "Healing",
    "FK_Diagnosis_Content_ID": 19
  },
  {
    "value": "Osteonecrosis",
    "Diagnosis_Code": "DIAG004",
    "NamaCategory": "Primary Category",
    "FK_Diagnosis_Content_ID": 2
  },
  {
    "value": "Malunion",
    "Diagnosis_Code": "DIAG004",
    "NamaCategory": "Healing",
    "FK_Diagnosis_Content_ID": 19
  }
]

I would like to create an array under the NameCategory property in case the NameCategory value is duplicated. The expected output should be as follows:

[
  {
    "NamaCategory": "Primary Category",
    "value":[
      {
        "value": "Osteonecrosis",
        "Diagnosis_Code": "DIAG002",
        "FK_Diagnosis_Content_ID": 2
      },
      {
        "value": "Osteonecrosis",
        "Diagnosis_Code": "DIAG004",
        "FK_Diagnosis_Content_ID": 2
      }
    ]
  },
  {
    "NamaCategory": "Healing",
    "value":[
      {
        "value": "Malunion",
        "Diagnosis_Code": "DIAG002",
        "FK_Diagnosis_Content_ID": 19
      },
      {
        "value": "Malunion",
        "Diagnosis_Code": "DIAG004",
        "FK_Diagnosis_Content_ID": 19
      }
    ]
  }
]

Since I am not very familiar with handling JSON, I am seeking assistance,

Can anyone provide guidance on how to manipulate this JSON data?

Answer №1

To achieve this, utilize the reduce method. This method will create a new array and then iterate through the old array to check if an object with a matching name as the NamaCategory exists in the new array using the findIndex function. If the object does not exist, a new object is created with the desired value and added to the new array. If the NamaCategory already exists, the value array is simply updated.

var originalArray = [{"value":"Osteonecrosis","Diagnosis_Code":"DIAG002","NamaCategory":"Primary Category","FK_Diagnosis_Content_ID":2},{"value":"Malunion","Diagnosis_Code":"DIAG002","NamaCategory":"Healing","FK_Diagnosis_Content_ID":19},{"value":"Osteonecrosis","Diagnosis_Code":"DIAG004","NamaCategory":"Primary Category","FK_Diagnosis_Content_ID":2},{"value":"Malunion","Diagnosis_Code":"DIAG004","NamaCategory":"Healing","FK_Diagnosis_Content_ID":19}];

var newArray = originalArray.reduce(function(accumulator, current) {
  // Find the index in the array where NamaCategory matches
  var findIfNameExists = accumulator.findIndex(function(item) {
    return item.NamaCategory === current.NamaCategory;
  })
  // If no such object exists in the new array where namecategory matches, create a new object
  if (findIfNameExists === -1) {
    let obj = {
      'NamaCategory': current.NamaCategory,
      "value": [current]
    }
    accumulator.push(obj)
  } else {
    // If the name category matches, push the value 
    accumulator[findIfNameExist].value.push(current)
  }
  return accumulator;

}, []);
console.log(newArray)

Answer №2

var items = [{"value":"Osteonecrosis","Diagnosis_Code":"DIAG002","NamaCategory":"Primary Category","FK_Diagnosis_Content_ID":2},{"value":"Malunion","Diagnosis_Code":"DIAG002","NamaCategory":"Healing","FK_Diagnosis_Content_ID":19},{"value":"Osteonecrosis","Diagnosis_Code":"DIAG004","NamaCategory":"Primary Category","FK_Diagnosis_Content_ID":2},{"value":"Malunion","Diagnosis_Code":"DIAG004","NamaCategory":"Healing","FK_Diagnosis_Content_ID":19}];

var result = [];
items.forEach(function(element) {
  var found = false;
  result.forEach(function(item) {
    if (element.NamaCategory == item.NamaCategory) {
      found = true;
    }
  });

  if (!found) {
    var newObj = {
      NamaCategory: element.NamaCategory,
      values: [element]
    }
    result.push(newObj);
  } else {
    result.forEach(function(item) {
      if (element.NamaCategory == item.NamaCategory) {
        item.values.push(element);
      }
    });
  }
});

console.log(result);

Simply iterate through the data and verify if an element exists in the final array. If it does, add the value to the values property; if not, create a new property in the final array.

Answer №3

let data = [
  {
    "value": "Osteonecrosis",
    "Diagnosis_Code": "DIAG002",
    "NamaCategory": "Primary Category",
    "FK_Diagnosis_Content_ID": 2
  },
  {
    "value": "Malunion",
    "Diagnosis_Code": "DIAG002",
    "NamaCategory": "Healing",
    "FK_Diagnosis_Content_ID": 19
  },
  {
    "value": "Osteonecrosis",
    "Diagnosis_Code": "DIAG004",
    "NamaCategory": "Primary Category",
    "FK_Diagnosis_Content_ID": 2
  },
  {
    "value": "Malunion",
    "Diagnosis_Code": "DIAG004",
    "NamaCategory": "Healing",
    "FK_Diagnosis_Content_ID": 19
  }
];

// Code to group data by 'NamaCategory'
let dataByNamaCategory = {};
data.forEach(({NamaCategory, ...otherProps}) => {
  if(NamaCategory in dataByNamaCategory){
    dataByNamaCategory[NamaCategory].value.push(otherProps)
  }else{
    dataByNamaCategory[NamaCategory] = { NamaCategory, value: [ otherProps ] };
  }
});

let groupedData = Object.values(dataByNamaCategory);
console.log(groupedData);
.as-console-wrapper{top:0;max-height:100%!important}

This code snippet demonstrates how to group data based on the 'NamaCategory' attribute using object destructuring in JavaScript. It may require some understanding of object destructuring and array manipulation. More information on object destructuring can be found 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

What are the best practices for managing live notifications with WebSocket technology?

I have developed a real-time chat application in React.js with Socket.io, but I want to implement a new feature. Currently, User A and User B can only communicate if they both have the chat open. I would like to notify User B with a popup/notification wh ...

Vue-based bot for telegram web application

Hey there, I've been working on integrating a web app with my chat bot, taking advantage of the new Telegram feature. Unfortunately, after adding the site, I'm encountering an issue where clicking the button opens up an empty page. It seems that ...

Transitioning from GeometryUtils.merge() to geometry.merge()

When upgrading from r66 to r67, a message pops up stating: DEPRECATED: GeometryUtils's .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead. The transition doesn't seem straightforward beca ...

The issue of jQuery's .last() function triggering multiple times with just a single click on the last

I currently have a set of tabs containing radio buttons and I need to trigger an event when the last option is selected (meaning any radio button within the final tab, not just the last radio button). Below is the HTML code: <div id="smartwizard" clas ...

Objective C - Organize JSON data into groups

I will attempt to explain my idea and what I hope to achieve. Here is the JSON structure: { "objects": [ { "title": "Title #1", "date": "1446930000" }, { "title": "Title #2", "date": "1437782400" }, { " ...

Is there a way to undo the changes made by the following execution using Javascript?

Similar Question: How can I delete a cookie using JavaScript? javascript:void(document.cookie=”PREF=ID=20b6e4c2f44943bb:U=4bf292d46faad806:TM=1249677602:LM=1257919388:S=odm0Ys-53ZueXfZG;path=/; domain=.google.com”); To undo the action perfor ...

Information is cleared before it is transmitted

Let's begin with the following code: JavaScript: function keyPressed(e) // function for key press event { if (e.keyCode == 13) // 13 represents the enter key { $(this).val(""); } } $(document).ready(function () { $(' ...

Modifying an array without altering the reference

Perhaps my approach is not quite right, so please provide feedback if necessary! Imagine having an Array that represents some valuable data. var initial = ['x', 'y']; var duplicate = initial; initial.push('z'); console.log(i ...

Unable to debug json.loads() code using pdb

I am curious to understand the inner workings of converting a JSON string to a Python dictionary using json.loads() For example: import json s = '{"a": 1, "b": 2}' # input json string d = json.loads(s) # output dictionary object To dive de ...

React App with Material UI V1-beta Integration

I just installed the Create React App example from Material-UI.com. curl https://codeload.github.com/callemall/material-ui/tar.gz/v1-beta | tar -xz --strip=2 material-ui-1-beta/examples/create-react-app Upon installation, I encountered the following erro ...

Navigating through different components in React is made possible with React Router

I have views in my application that depend on each other. For example, in one view a user can choose an item from a list (generated on the server), and in the next view they can perform operations on that selected item. The item is passed to the second v ...

What is causing the malfunction in this code? (Regarding the key and value variable objects)

var elements = []; var attribute1 = $(index).attr('class'); //or any string var attribute2 = $(index).html(); //or any string elements.push({ attribute1: attribute2 }); When I run this code, the output I receive is: this Why am I unable to set ...

The issue of empty strings not converting to null when passing a JSON object to a controller

My observation in ASP.NET Core 2.1 is quite the opposite of a similar question raised about string.empty being converted to null when passing JSON object to MVC Controller. In my case, when a JSON object with properties containing empty strings is sent ba ...

Images do not appear on Bootstrap Carousel as expected

I am facing an issue where the images are not displaying on my bootstrap carousel or when I try to display them individually using their class. I am utilizing bootstrap and express for my project. I have verified multiple times that the file path to the im ...

Puppeteer does not support the use of multiple proxies concurrently

How can I effectively set up multiple proxies with puppeteer? Here is the approach I have taken: const puppeteer = require('puppeteer'); (async () => { let browsers = []; const proxies = [ 'socks5://myuser: ...

Maintaining the "Date" value in React Native DatePickerIOS when returning from other pages

In my scenario, I am using the DatePickerIOS component. The example in the documentation initializes a new Date() and uses state to store and update the Date value. However, when navigating to another page and returning, the time changes and I find myself ...

Using Jquery to add a list after parsing JSON data stored in localStorage

I've been stuck on this issue for quite some time now. The problem I'm facing involves checking the localStorage to see if there's a cached JSON string available. If there is, I load it and convert it back into a JSON object. If not, I make ...

A guide to downloading a file linked to Javascript with the help of Java

I have a unique request here. I am looking for a solution using HttpUrlConnection that can interact with JavaScript directly on a webpage, instead of relying on Selenium as a workaround. Can anyone assist me with this? The webpage contains a link (hidden ...

Activate the date-picker view when the custom button is clicked

Utilizing this library for date-picker functionality has been quite beneficial. I am currently working on a feature that involves opening the date-picker upon clicking a custom button. The default input is functioning properly. <input name="pickerFromD ...

Learn how to dynamically switch the background image of a webpage using a button in AngularJS

Hey there, I'm currently working on incorporating interactive buttons into my website to give users the ability to customize the background. I've been experimenting with Angular to achieve this feature. So far, I've managed to change the ba ...