Reorganizing JSON data with ES6 techniques

I have a scenario where I need to update tire quantities in an array like this:

tires: [{
  name: "fancyProduct1",
  quantity: 1
}, {
  name: "fancyProduct1",
  quantity: 1
}, {
  name: "fancyProduct1",
  quantity: 1
}, {
  name: "fancyProduct2",
  quantity: 1
}];

My goal is to achieve the following structure:

tires: [{
  name: "fancyProduct1",
  quantity: 3
}, {
  name: "fancyProduct2",
  quantity: 1
}]

Does anyone have any suggestions on the best approach to tackle this?

Answer №1

To consolidate the array into a single object, you can utilize the reduce method. Afterwards, convert the object into an array using Object.values.

let vehicles = [{"type":"car1","quantity":1},{"type":"car1","quantity":1},{"type":"car1","quantity":1},{"type":"car2","quantity":1}];

let finalResult = Object.values(vehicles.reduce((acc, {type, quantity}) => {
  acc[type] = acc[type] || {type, quantity: 0}
  acc[type].quantity += quantity;
  return acc;
}, {}));

console.log(finalResult);

Answer №2

To achieve this, you can use the Reduce method as shown below:

var items = { books: [ {title: "The Great Gatsby", quantity: 1}, {title: "To Kill a Mockingbird", quantity: 2}, {title: "1984", quantity: 3}] };

var finalResult = items.books.reduce((accumulator,currentItem) => {

    if (!accumulator[currentItem.title]) {
       accumulator[currentItem.title] = { title: currentItem.title, quantity: 0};
    }

    accumulator[currentItem.title].quantity++;

    return accumulator;
}, {});

var finalArrayResult = Object.values(finalResult);
console.log(finalArrayResult);

Answer №3

You can easily iterate over the items in an array using Array.forEach() function. To check if a specific item exists in an array and manipulate your logic accordingly, you can use Array.find().

Here's how you could structure your code:

var result = [];

tires.forEach(function(el) {
  let found = result.find(o => o.name === el.name);
  if (found) {
    found["quantity"] += el["quantity"];
  } else {
    result.push(el);
  }
});

Check out this demo:

var tires = [{
  name: "fancyProduct1",
  quantity: 1
}, {
  name: "fancyProduct1",
  quantity: 1
}, {
  name: "fancyProduct1",
  quantity: 1
}, {
  name: "fancyProduct2",
  quantity: 1
}];

var result = [];

tires.forEach(function(el) {
  let found = result.find(o => o.name === el.name);
  if (found) {
    found["quantity"] += el["quantity"];
  } else {
    result.push(el);
  }
});

console.log(result);

Answer №4

One possible solution is to implement the following...

let newTires = tires.map(number => (
 // Include logic here to generate a new array with attributes from items in tires. 
console.log(number);  // This will display the available properties of the current item in the console. 
)};

I trust this information proves beneficial.

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

Trouble arises when adding a .js script to the webpage

I'm feeling quite puzzled by this small piece of code, as it appears to be the simplest thing you'll come across today. Despite that, I can't help but seek guidance because I've been staring at it for what feels like an eternity and can ...

ExpressJs responds with an empty JSON object

During the validation of a mongoose schema within 'pre' of parallel middleware schema.pre('save', true, function (next, done) { if(...) { next(new Error('Some error message')); } next(); }); After returning an err ...

Sorting through a Json array

I'm new to working with JSON and struggling to filter an array to retrieve all values (store) where id_estado=1. Any suggestions on how I should tackle this? JA1= [{"id_estado":"1","tienda":"Aurrera"},{"id_estado":"1","tienda":"Walt-Mart"},{"id_esta ...

An error occurred when trying to convert a com.google.gson.JsonObject to a com.google.gson.JsonArray

I am encountering an issue with parsing a JSON response. Here is the response data: { "deal": { "categorie": { "description": "Offres Shopping", "idcategorie": "1", "nom": "Shopping" }, "cond ...

Confirmation for deletion in HTML form

Is there a way I can include a confirmation message for deleting an item on my form button? Any suggestions on which JavaScript code to use? <script type="text/javascript"> function confirmDelete() { return confirm("Are you sure you want to delete ...

How can I properly initialize React components?

I am currently learning React.js and experimenting with a progress bar animation. I stumbled upon this code that I would like to incorporate into my project, but I am unsure of where to place it. Check out the code here! The JavaScript code in question i ...

SonarQube flagging a suggestion to "eliminate this unnecessary assignment to a local variable"

Why am I encountering an error with SonarQube? How can I resolve it since the rule page does not offer a specific solution? The suggestion is to eliminate the unnecessary assignment to the local variable "validateAddressRequest". validateAddress() { ...

How to Identify and Print a Specific Property in a JSON Object using Node.js?

Hey there, I'm having trouble extracting the trackName from the JSON object provided here. I've tried accessing it using this code: console.log(res.text.results[0].trackName); but unfortunately, I keep getting this error message: TypeError: Cann ...

Exporting functions using reactjs and babel

I'm currently working on a project that involves using reactjs, transpiled by babel with es2015 and react transforms configured in my .babelrc file. In the initial stages of refactoring, I realized that many of the classes should actually be functions ...

Loading the children of a specified div ID using AJAX

Imagine having the following code: $('a').each(function() { $(this).click(function(e) { e.preventDefault(); var href = $(this).attr('href'); $('#somediv').load(href + ' #foo'); }); }) ...

having issues with my expressjs router functionality

Embarking on my MEAN stack journey, I have been immersing myself in tutorials. It has become clear that everyone does not approach the logic in the same way. However, I find myself stuck on two particular examples. Example One: // server.js var express = ...

Display current weather conditions with the Open Weather API (featuring weather icons)

Hello everyone, I need some help from the community. I am currently working on a weather app using the openweather API. However, I'm facing an issue with displaying the weather conditions icon for each city. I have stored every icon id in a new array ...

"We are unable to set a value for a global array unless we utilize the .push() method

It's puzzling that I can't populate a global array without using the .push() method. (function() { var globalEmail = []; var testUpdate = function() { var arr = [1, 2, 3]; if (globalEmail.length > 1) { gl ...

Linking to an external website using AngularJS for navigation

After developing my angular app, I included an array of menu items that are displayed in the template: <nav id="menu"> <ul> <li ng-repeat="i in menuItems" ui-sref="{{ i | removeSpacesThenLowercase }}" ui-sref-active=" ...

Developing custom functions in ejs for individual posts

In my blog, I have a feed where all users' posts are displayed dynamically using ejs. There is a comment section that remains hidden until the user clicks the comments button. Below is a snippet of my ejs file: <% posts.forEach(post => { %> ...

Sending JSON data from an Android device to a server using PHP

I am facing some issues with locating and utilizing the JSON object that my application sends to my server. Here is the code snippet: InputStream inputStream = null; String result = ""; try { // 1. create HttpClient HttpClient h ...

Send the Children prop to the React Memo component

Currently, I am in the stage of enhancing a set of React SFC components by utilizing React.memo. The majority of these components have children and the project incorporates TypeScript. I had a notion that memo components do not support children when I en ...

(Definition) What is the proper way to reference a variable inside another variable?

Currently, my project is using inconsistent terminology when referring to variables, and I need to clarify this issue. Let's take an object defined in this way: var anObject = { a: { value1: 1337, value2: 69, value3: "420 ...

Refreshing html in nodejs after a fetch promise remains in a pending state

I am facing an issue with the `then` method in Express and Node.js as it is logging a promise that remains pending. edit().then(data => console.log(data)); Below is the code for the edit function: async function edit(data, id) { let response = aw ...

Preventing an RxJS Observable interval: A step-by-step guide

I am facing a unique scenario where I am using an RxJS interval, but I might need to abruptly stop it at any point. I thought there would be a simple method like cancel() or stop() similar to clearTimeout for intervals. Is there a way to stop an interval o ...