Separate the JSON array according to the type of suggestion it's being given

My JSON array is structured like this:

[
  {
    "characterID": 0,
    "description": "Series 1",
    "id": 1,
    "seriesID": 0,
    "status": "ACCEPTED",
    "type": "SERIES",
    "userID": 1
  },
  {
    "characterID": 0,
    "description": "Series 2",
    "id": 2,
    "seriesID": 0,
    "status": "ACCEPTED",
    "type": "SERIES",
    "userID": 1
  },
  {
    "characterID": 0,
    "description": "Character 1",
    "id": 1,
    "seriesID": 25,
    "status": "ACCEPTED",
    "type": "CHARACTER",
    "userID": 1
  },
  {
    "URL": "https://previews.123rf.com/images/aquir/aquir1311/aquir131100316/23569861-sample-grunge-red-round-stamp.jpg",
    "characterID": 853,
    "description": "Picture 1",
    "id": 1,
    "seriesID": 25,
    "status": "ACCEPTED",
    "type": "IMAGE",
    "userID": 1
  },
  {
    "URL": "https://c.tenor.com/uEjQxCwAWfgAAAAC/sample.gif",
    "characterID": 1,
    "description": "Gif 1",
    "id": 1,
    "seriesID": 1,
    "status": "ACCEPTED",
    "type": "GIF",
    "userID": 1
  },
  {
    "characterID": 0,
    "description": "Idea 1",
    "id": 1,
    "seriesID": 0,
    "status": "ACCEPTED",
    "type": "IDEA",
    "userID": 1
  }
]

I am interested in splitting the JSON into different segments based on the type it contains within the array.

I am currently working in Javascript / Vue and would appreciate any solutions to achieve this segmentation.

Answer №1

Utilizing Array.reduce will provide an effective solution in this scenario.

For demonstration purposes, an example is presented below.

var data = JSON.parse('[{"characterID":0,"description":"Series 1","id":1,"seriesID":0,"status":"ACCEPTED","type":"SERIES","userID":1},{"characterID":0,"description":"Series 2","id":2,"seriesID":0,"status":"ACCEPTED","type":"SERIES","userID":1},{"characterID":0,"description":"Character 1","id":1,"seriesID":25,"status":"ACCEPTED","type":"CHARACTER","userID":1},{"URL":"https://previews.123rf.com/images/aquir/aquir1311/aquir131100316/23569861-sample-grunge-red-round-stamp.jpg","characterID":853,"description":"Picture 1","id":1,"seriesID":25,"status":"ACCEPTED","type":"IMAGE","userID":1},{"URL":"https://c.tenor.com/uEjQxCwAWfgAAAAC/sample.gif","characterID":1,"description":"Gif 1","id":1,"seriesID":1,"status":"ACCEPTED","type":"GIF","userID":1},{"characterID":0,"description":"Idea 1","id":1,"seriesID":0,"status":"ACCEPTED","type":"IDEA","userID":1}]');


const grouped = data.reduce((a, v) => {
  if (!a[v.type]) a[v.type] = [];
  a[v.type].push(v);
  return a;
}, {});

console.log(grouped);

Answer №2

You can employ the reduce method to generate a fresh object with types as keys:

var result = data.reduce((accumulator, value) => {
if (!accumulator[value.type]) {
    accumulator[value.type] = [value];
} else {
    accumulator[value.type].push(value)
}
return accumulator;

}, {})

The outcome will resemble:

{
   "SERIES":[
      {
         "characterID":0,
         "description":"Series 1",
         "id":1,
         "seriesID":0,
         "status":"ACCEPTED",
         "type":"SERIES",
         "userID":1
      },
      {
         "characterID":0,
         "description":"Series 2",
         "id":2,
         "seriesID":0,
         "status":"ACCEPTED",
         "type":"SERIES",
         "userID":1
      }
   ],
   "CHARACTER":[
      {
         "characterID":0,
         "description":"Character 1",
         "id":1,
         "seriesID":25,
         "status":"ACCEPTED",
         "type":"CHARACTER",
         "userID":1
      }
   ],
   "IMAGE":[
      {
         "URL":"https://previews.123rf.com/images/aquir/aquir1311/aquir131100316/23569861-sample-grunge-red-round-stamp.jpg",
         "characterID":853,
         "description":"Picture 1",
         "id":1,
         "seriesID":25,
         "status":"ACCEPTED",
         "type":"IMAGE",
         "userID":1
      }
   ],
   "GIF":[
      {
         "URL":"https://c.tenor.com/uEjQxCwAWfgAAAAC/sample.gif",
         "characterID":1,
         "description":"Gif 1",
         "id":1,
         "seriesID":1,
         "status":"ACCEPTED",
         "type":"GIF",
         "userID":1
      }
   ],
   "IDEA":[
      {
         "characterID":0,
         "description":"Idea 1",
         "id":1,
         "seriesID":0,
         "status":"ACCEPTED",
         "type":"IDEA",
         "userID":1
      }
   ]
}

Answer №3

Uncertain if you wish to divide and store in separate arrays, but if so, you can attempt the following:

const data = [
  {
    "characterID": 0,
    "description": "Series 1",
    "id": 1,
    "seriesID": 0,
    "status": "ACCEPTED",
    "type": "SERIES",
    "userID": 1
  },
  {
    "characterID": 0,
    "description": "Series 2",
    "id": 2,
    "seriesID": 0,
    "status": "ACCEPTED",
    "type": "SERIES",
    "userID": 1
  },
  {
    "characterID": 0,
    "description": "Character 1",
    "id": 1,
    "seriesID": 25,
    "status": "ACCEPTED",
    "type": "CHARACTER",
    "userID": 1
  },
  {
    "URL": "https://previews.123rf.com/images/aquir/aquir1311/aquir131100316/23569861-sample-grunge-red-round-stamp.jpg",
    "characterID": 853,
    "description": "Picture 1",
    "id": 1,
    "seriesID": 25,
    "status": "ACCEPTED",
    "type": "IMAGE",
    "userID": 1
  },
  {
    "URL": "https://c.tenor.com/uEjQxCwAWfgAAAAC/sample.gif",
    "characterID": 1,
    "description": "Gif 1",
    "id": 1,
    "seriesID": 1,
    "status": "ACCEPTED",
    "type": "GIF",
    "userID": 1
  },
  {
    "characterID": 0,
    "description": "Idea 1",
    "id": 1,
    "seriesID": 0,
    "status": "ACCEPTED",
    "type": "IDEA",
    "userID": 1
  }
];

const seriesData = [];

data.map(eachData => {
  if (eachData.type === 'SERIES'){
    seriesData.push(eachData);
  }
});
console.log('Series Data =>', seriesData);

Feel free to apply the same logic for other type values as well.

Answer №4

If you're looking for a simple solution, consider using a utility library such as lodash. Specifically, the groupBy method can be very helpful.

_.groupBy(data, 'type');// {SERIES: Array(2), CHARACTER: Array(1), IMAGE: Array(1), GIF: Array(1), IDEA: Array(1)}

UPDATE:(alternative vanilla JavaScript approach) To achieve the same result without using any external libraries, you can utilize the Map object. This object stores key-value pairs, where the key represents the type and the value is an array of entries belonging to that type. Optional chaining ?. and nullish coalescing operator ?? are used here.

let map = new Map()
for(entry of data){
    const type = entry?.type ?? "untyped";
    map.set(type, [...map.get(type)??[],entry])
}
// Map(5) {'SERIES' => Array(2), 'CHARACTER' => Array(1), 'IMAGE' => Array(1), 'GIF' => Array(1), 'IDEA' => Array(1)}

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

An unexpected { token error was encountered by Jest while running a React application

I am facing a persistent issue that I just can't seem to resolve. Despite trying numerous solutions found online, nothing seems to fix it. Below are the configurations: package.json { "scripts": { "test": "jest --no-cache", ...

Exploring the functions of `map` and `filter` in the world of

Consider this input: var m = [{ name: 'foo', routes: [{verb: 'post', path: '/foo1'}, {verb: 'get', path: '/foo2'}] }, { name: 'bar', routes: [{verb: 'put', path: ...

Repeated parameters when making a second login request with axios and sending data in url-encoded format

Implementing token-based authentication and sending urlencoded data via axios. Passing the user and password to the axios function with all parameters set as per documentation. import axios from 'axios' const params = new URLSearchParams() param ...

Angular 5 Service Unit Testing for UPDATE Function

Currently, I am implementing a stepper feature with back, step, next steps. On the last step, when the user clicks 'done,' I need to call a service to update user data. While I have successfully tested the backStep() and nextStep() methods, I now ...

Selenium EventFiringWebDriver JavaScript: There is a SyntaxError due to a missing closing parenthesis after an argument in

Attempting to run a javaScript command through the EventFiringWebDriver class in Selenium. EventFiringWebDriver eventFiringWebDriver = new EventFiringWebDriver(driver); eventFiringWebDriver.executeScript("document.querySelector('[ng-reflect-title=&ap ...

Tips for managing the output of an asynchronous function in TypeScript

The casesService function deals with handling an HTTP request and response to return a single object. However, due to its asynchronous nature, it currently returns an empty object (this.caseBook). My goal is for it to only return the object once it has b ...

Having trouble with special characters when using json.dumps()?

I need help with serializing a Python dictionary into JSON format in order to store it in a database. obj = json.dumps({ 'name':'کوروش' }, sort_keys=True, indent=-1, ensure_ascii=False).encode('utf-8') Despite s ...

Google Chrome successfully transmits two variables with AJAX, whereas Mozilla Firefox does not send them

Having an issue with sending two values through ajax - currently only one value is being sent in Mozilla browser. Ajax script: $('#post_submit').click(function() { event.preventDefault(); var great_id = $("#post_container_supreme:first").attr(" ...

Vue.js - When Property is Undefined and How to Render it in Browser

My experience with Vue has been quite puzzling. I've encountered an issue while trying to render a nested property of an object called descrizione, and although it does work, I keep receiving a warning from Vue in the console: TypeError: Cannot rea ...

Converting a JSON array containing multiple arrays into a SQL table

I received a JSON response from an API that looks like this: { "series":[ { "series_id": "SER_ID_1", "data": [ ["20200101", 1.0 ], ["20200102" ...

Problems with implementing JavaScript code in a WebView

I am currently working on an android WebView project where I have managed to change the background color to orange with this code snippet. @Override public void onPageFinished(WebView view, String url) { wv.loadUrl("jav ...

javascript the unseen element becomes visible upon page loading

my website has the following HTML snippet: function getURLParameters() { var parameters = {}; var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { parameters[key] = value; }); return param ...

What is the method for allowing tooltips to disappear when clicked on?

Is there a way to prevent a tooltip from hiding unless it is clicked on? Would using a popover be a better solution? var Button = document.querySelector('.Button'); $(Button).attr("data-toggle", "tooltip"); $(Button).attr("data-placement", "top ...

Getting headers from an HTTP response in VueJS is a common task that many developers encounter

I am utilizing axios to fetch data from the backend. After sending a request, I receive a response; however, I am struggling to read some of my headers. The headers that I need to access are 'content-type', 'content-length', 'x-wp- ...

Vuetify Container with a set maximum width that remains fixed

I recently started developing a web application using Vue.js and Vuetify (https://vuetifyjs.com/en/). Currently, I have a basic layout with 3 columns. However, I noticed that the width of these columns is restricted to a maximum of 960px due to some defau ...

A beginner's guide to retrieving random names and images from JSON data for every object using JavaScript

I have a creative idea for a random ruffling game, where it picks a user's name and image randomly. However, I'm facing an issue with ensuring that each image matches the correct user when selected randomly. I want to make sure that every objec ...

Synchronous execution of functions in Node.js

I need to ensure that func2 is only called after func1 has completed its execution. { func1(); func2();// } However, the issue arises when func1() starts running and func2() does not wait for it to finish. This leads to a runtime error as func2() require ...

Troubleshooting issue with DOM not refreshing after making a $http POST request in a MEAN

I am working on an app that interacts with a Mongo database through CRUD operations. Currently, I have a form input where users can add elements, and I want these elements to appear below the form in real-time as they are added. However, at the moment, the ...

Are there any uncomplicated JavaScript tools for creating spreadsheets?

I am in the process of developing a basic web-based expense calculator using asp.net web forms. Each cell will contain a text box, and the objective is to save each value (excluding the totals) to a database. I plan to have an expense table and an expense_ ...

Jquery Fails to Execute When Clicking on Radio Button

Whenever a user selects a radio button, I want to display an alert box. I have already written the jQuery code to achieve this. Here is my implementation: <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></ ...