Aggregating JSON data by comparing and combining corresponding keys

Before appending to a JSON object, I want to compare the values of keys and if they are the same, add the values together instead of simply appending.

Here is the current structure:

{"carset": {
          "location1": [
                      {"car": "volvo", "count": 5},
                      {"car": "mazda", "count": 7},
                      {"car": "toyota", "count": 10},
                     ]
             }
  }

During my for loop:

newcar = 'volvo';
newcount = 6;
cars[i] = ({car: newcar, count: newcount});

I am looking for a way to identify that 'volvo' already exists in the JSON object and add the new count value to the existing one. Your assistance is greatly appreciated!

Answer №1

To effectively compare, you have two options - either iterate through all items in the location1 array or simplify the comparison process by adjusting your JSON structure.

json = {
 'carset' : {
    'location-vehicles' : {
      'honda'  : 3,
      'ford'   : 6,
      'chevrolet' : 9
    }
  }
}

function addVehicle(vehicles, vehicle) {
  var theVehicle = vehicles[vehicle];
   if ( theVehicle == undefined ) {
      vehicles[vehicle] = 1;
   } else {
      vehicles[vehicle] = theVehicle + 1;
   }
   return vehicles[vehicle];
}

addVehicle(json.carset['location-vehicles'], 'honda');

Answer №2

function isCarPresent(name) {
    for (var key in garage.cars.location) {
        if (garage.cars.location[key].name == name) {
            return true;
        }
    }

    return false;
}

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

Converting search results into JSON format in PHP/MySQL

My MySQL database table is structured as follows, with the shows_id field formatted in JSON: id | assign_id | rights | party |shows_id ---+-------------+------------+------------+--------- 1 |4 | 12 | xyz | ["2","3"," ...

What is the best way to transmit the attributes of an object with a defined state in one React component to another component using a link and display them?

I currently have two components and one route in my project. I am trying to pass the properties of the place object from one component to another so that I can display them accordingly. The first component holds the list of places in its state, where I map ...

vee-validate remains consistent in its language settings

Having trouble changing the error message in vee-validate, any suggestions on how to fix this? import VeeValidate from "vee-validate"; import hebrew from "vee-validate/dist/locale/he"; Vue.use(VeeValidate, { locale: "he", dictionary: { he: { me ...

Create seamless communication between Angular application and React build

I am currently engaged in a project that involves integrating a React widget into an Angular application. The component I'm working on functions as a chatbot. Here is the App.tsx file (written in TypeScript) which serves as the entry point for the Rea ...

Challenges encountered in converting JSON objects into an HTML table

My goal is to convert a JSON object into an HTML Table using the following code: JSONSelect.forEach(selecRow, options, function (queryResult) { var sem = $.trim(JSON.stringify(queryResult, null, ' ')); console.log(sem); $.getJSON(&ap ...

How is it that the bird is able to navigate around the ledges without any collisions?

I'm currently developing a flappy bird game using phaser.js. The issue I'm facing is that the player doesn't collide with the ledges in the game. Also, I would like to know how to implement camera movement (similar to Flappy Bird). Any addi ...

How can I restrict the number of characters per line in a textarea using javascript or jQuery?

Is there a method to control the number of characters per line in a textarea? For example, on lines 1-3 of the textarea, only 20 characters can be entered, while on subsequent lines, up to 50 characters are allowed. The current structure of the textarea l ...

Undefined reference in $http

I am puzzled as to why I am getting an undefined index with the code snippet below. Despite thoroughly checking everything, I cannot seem to identify what is causing the issue. $http({ url: "php/mainLoad.php", method: "GET", data: {"userId" ...

Using React hook form to create a Field Array within a Dialog component in Material UI

I have a form with custom fields added via Field Array from react-hook-form, and everything is functioning properly. However, I recently implemented drag and drop functionality for the property items to allow reordering them. Due to the large number of fie ...

What is the method for retrieving an array or object that contains a collection of files designated for uploading within the jQuery file upload plugin?

Currently, I have successfully integrated a form into my Rails site and set up the jQuery file upload plugin. The upload form functions properly with the ability to select multiple files and utilize all ajax upload features. However, a challenge I am faci ...

A .NET Core web API that is configured to receive input in camelCase and provide output

I currently have a .NET Core Web API that by default returns JSON in camelCase format. However, I wanted to change this behavior and switch it to snake_case. To achieve this, I added the following code snippet in my ConfigureServices: services.AddMvc().Ad ...

Using regular expressions to enable scientific notation in a numeric text field

I'm looking to create a validation system for numbers with scientific notation (using 'e', '+', '-', '.') using regex. I've tried some expressions but they are not working as expected. For Regular Numbers: ...

Why doesn't the toggle function with the ! operator work when the page loads in JavaScript

Seeking assistance with an onClick event in Angular.js (ng-click) to toggle the color of a table row upon clicking. Initial implementation is as follows: <tr> <td ng-class="{'setType': types.isTypeSet('TYPE') == tr ...

Issues encountered when utilizing a provider alongside a controller for implementing Highcharts visualizations in angularjs

I've been working on an Angular web application that incorporates highcharts (highcharts-ng) integration. My approach was to set up a factory provider where I defined my chart configuration options object: angular.module('socialDashboard') ...

Saving files in ElasticSearch with a generic JsonNode using the Spring Data framework

I have a requirement to store diverse json payload data in an Elasticsearch index using Spring Data. To achieve this, I am utilizing the following entity structure: @Document(indexName = "message") public class Message { @Id ...

The knockout click event isn't functioning properly for a table generated by ko.computed

My goal is to connect a table to a drop-down menu. Here are the key points of what I'm trying to achieve: The drop-down should list MENUs. Each MENU can have multiple MODULES associated with it, which will be displayed in the table based on the ...

JavaScript fails to accurately arrange list items

Within my array of objects, I have a list of items that need to be sorted by the fieldName. While the sorting generally works fine, there are certain items where the sorting seems off and does not function properly. Here is the code snippet responsible fo ...

FileChooser - Displaying an error message when attempting to save a JSON file as a PNG or alternative format

To create dummy JSON data in JavaFX, Instantiate a FileChooser object and save the dummy JSON data into a file named Products.json If the user tries to save the file with a different extension like .png or .xml, an error message should be displayed saying ...

Run a query upon loading the page

I would like to run a query during the onload event. How can I achieve this? Here is my code. This is the specific query that needs to be executed. <?php mysql_query("UPDATE `requests` SET `stat_id`= 3 WHERE `proj_id`='".$_GET['projid&apo ...

Removing items from an array in Angular when a checkbox is checked

I'm looking to iterate through a checklist and remove completed items from the array. Here's my current code: app.controller("MainController", ["$scope",function($scope) { $scope.list = [{ text: 'Figure your stuff out', done: ...