Unlocking JSON data with identical keys using JavaScriptLearn how to access JSON data with

I need help converting my JSON training data that includes classes and sentences into a different format.

[
  { class: 'Reservation', sentence: 'make reservation' },
    { class: 'Reservation', sentence: 'do reservation' },
    { class: 'Greetings', sentence: 'Hello' },
    { class: 'Greetings', sentence: 'Good Morning' }
]

How can I transform it into the following format?

[
  { class: 'Reservation', sentence: ['make reservation', 'do reservation'] },
  { class: 'Greetings', sentence: ['Hello', 'Good Morning'] }
]

Answer №1

To create a new array, iterate through each object and add them based on certain conditions. Before adding an object to the new array, validate if it already exists in order to avoid duplicates. Instead of adding a duplicate, append the current sentence to the existing object.

Follow these steps:

  1. Initialize an empty array
  2. Iterate over the array containing objects (the original object array)
  3. Verify if the object with a specific class value already exists
  4. If not found, add a new object to the new array with the class value and a sentence array that includes the current sentence as the first item (refer to the provided code snippet). If found, simply push the current sentence to the existing object's sentence array.

var data = [
  { class: 'Reservation', sentence: 'make reservation' },
  { class: 'Reservation', sentence: 'do reservation' },
  { class: 'Greetings', sentence: 'Hello' },
  { class: 'Greetings', sentence: 'Good Morning' }
]

var dataFormatted = [];

for(var i = 0; i < data.length; i++){
    //document.write(JSON.stringify(data[i]));
  const existingClass = dataFormatted.find(d => d.class == data[i].class);
  if(existingClass){
    existingClass.sentence.push(data[i].sentence)
  } else{
    dataFormatted.push({
        class: data[i].class,
      sentence: [data[i].sentence]
    });
  }
}

document.write(JSON.stringify(dataFormatted))

I hope this explanation is clear.

Answer №2

If you need to manipulate a json array, you can iterate through it and create a new array by either adding elements to an existing list or creating a new one if no match is found:

const jsonData = [
  { category: 'Fruit', item: 'apple' },
  { category: 'Fruit', item: 'orange' },
  { category: 'Vegetable', item: 'carrot' },
  { category: 'Vegetable', item: 'spinach' }
]

const newData = []
jsonData.forEach((element) => {
  let matchedCategory = newData.find(e => e.category === element.category);
  if (matchedCategory) {
    matchedCategory.item.push(element.item);
  } else {
    newData.push({
      category: element.category,
      item: [element.item]
    });
  }
})

console.log(newData)

Answer №3

Maybe you're looking to combine data in this way:

function combineData(data){
  const result = [];
  for(let i=0, obj, prev, len=data.length; i<len; i++){
    obj = data[i]; 
    prev = result.find(d=>d.class === obj.class);
    if(prev){
      prev.sentence.push(obj.sentence);
    }
    else{
      result.push({class:obj.class, sentence:[obj.sentence]}); 
    }
  }
  return result;
}
const testData = [
  { class: 'Reservation', sentence: 'make reservation' },
  { class: 'Reservation', sentence: 'do reservation' },
  { class: 'Greetings', sentence: 'Hello' },
  { class: 'Greetings', sentence: 'Good Morning' }
];
console.log(combineData(testData));

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

No visible alterations were observed to the object following the invocation of JSONDecoder

I'm facing an issue with parsing JSON data into a struct using JSONDecoder in my function called by viewDidLoad. Even though the API call works correctly in postman, I can't seem to print the movie data in the console when I try to access it. Ins ...

Utilizing React JS with Material-UI Autocomplete allows for seamlessly transferring the selected item from the renderInput to the InputProps of the textfield component

Exploring the functionality of the updated version of Autocomplete, my goal is to ensure that when an element is chosen from the dropdown menu, the input format of the text field will be modified to accommodate adding a chip with the selected text. Is the ...

What is the best way to place content in a single div without it being divided into several separate boxes

Here is my code snippet: <div class="col-md-9"> <div id="statbox"> {% for obj in product_type %} {% for obj1 in vastu %} <script type="text/javascript"&g ...

What is causing the search filter in the App.js code to malfunction?

After fetching a list of names from an array using the Fetch method, I attempted to implement a search filter by adding the resetData() method in my componentDidMount. Unfortunately, this resulted in an error as shown here: https://i.stack.imgur.com/1Z7kx. ...

Various filters have been utilized on an array of objects

Within one of my Vue components, the code structure is as follows: <li class="comment" v-for="comment in comments"> ... </li> Accompanied by a computed method: computed: { comments() { // Here lies the logic for filtering comment ...

Flask web framework fails to deliver Jquery ajax json get call

I've been attempting to make a simple jQuery AJAX call to fetch JSON data, but I'm running into issues and struggling to understand why. Below is the code. It appears correct to me. $(document).ready(function() { function onDataReceived (d ...

Having issues with jQuery when trying to select only a single checkbox?

I have created a table with four rows and eight columns, each containing a checkbox. My goal is to allow only one checkbox to be checked per row. I am attempting to achieve this using jQuery. While it works in jsfiddle, I am experiencing difficulties in ge ...

"Implementing legends in charts with c3.js and JSON data: A step-by-step guide

Utilizing the C3 chart library to showcase data in my project, I aim to display legends (labels) instead of numbers on the AxisX: Data JSON format: [ {"Label":"DQUA","Aut":3.75,"NoAut":3.75,"CM":32}, {"Label":"DPRO","Aut":43.9,"NoAut":0,"CM":144} ...

Having trouble parsing JSON data using JSONArray in Android

My goal is to convert a json string into a JSONArray, but I keep encountering a jsonexception. What's puzzling is that the error message seems incorrect after debugging. Here is the crucial part of the code: ... HttpResponse response = httpclient. ...

What is the best way to keep tab content fixed when switching?

I've successfully implemented tab switching, but I need to make the content fixed. How can I achieve this so that no matter the length of the content, it remains fixed in its position when switching tabs? The current issue is that when the content is ...

Having trouble retrieving parameters within the expressjs router.delete endpoint implementation

Check out my code snippet below where I utilized Express router and Mongoose Model. I am encountering an issue accessing the id parameter. router.delete('/task/:id', function (req, res) { Task.remove({ ...

No specification has been provided for the delivery

I'm currently working with the Meteor framework and I am attempting to send an uploaded file (HTML input) from the client to the server using the npm package Delivery. Below is my code: Client side : var socket = io.connect('http://0.0.0.0 ...

JavaScript equivalent code to C#'s File.ReadLines(filepath) would be reading a file line

Currently in my coding project using C#, I have incorporated the .NET package File.ReadLines(). Is there a way to replicate this functionality in JavaScript? var csvArray = File.ReadLines(filePath).Select(x => x.Split(',')).ToArray(); I am a ...

failure to properly assign a property during model update in mongoose

My BaseSchema contains logic that should set values for two properties when a new Model is created: schema.pre("save", function (next) { if (!schema.isNew) { this.createDate = new Date(); this.createBy = "kianoush"; } next(); }); If updating, ...

Is it correct to use React Router's useNavigate with a useEffect hook for navigation?

I am a beginner to React and I have been working on creating a loading/greeting page that automatically navigates to the next page after a few seconds. In React Router v6, there is a useful hook called useNavigate() which allows you to control navigation. ...

Tailored NodeJS compilation incorporating JavaScript modules

Can NodeJS be built together with specific JavaScript modules? I am aware that for native modules, node-gyp can assist with this, but I am unsure about how to accomplish this with JavaScript modules. My goal is to use a custom application without needing t ...

Create a JSON file on the fly

I am in need of performing a post request using a JSON file. The current structure of the JSON is as follows: { "compositeRequest" : [{ // Account "method" : "POST", "url" : &quo ...

Search for data in a JSON file using PHP and retrieve the desired result

Looking for a specific item from my JSON File and its corresponding ID? Here's the code snippet to search for the item name based on the provided ID. CODE: $jsonitem = file_get_contents("data.json"); $objitems = json_decode($jsonitem); $findIt ...

Tips for fading the text of list items when their checkbox is marked as done?

I am trying to figure out how to gray out a list item when its checkbox is checked. The code I currently have takes text input from a textbox and adds it to an unordered list when the add button is clicked. Each list item contains a checkbox within it. My ...

Validating Responses in RESTful APIs

As I work on creating a RESTful API, I find myself pondering the ideal format for validation error messages. Take, for instance, my account creation endpoint which accepts a JSON object: user: { first_name: string, last_name: string, address: { ...