Utilize nested keys to reduce an array of objects in JavaScript

I am facing a challenge with an array that contains a list of JavaScript objects. My goal is to utilize the reduce function to transform it into a single object with nested key groupings.

This is how the initial array appears:

[
  {
   "product": 1,
   "date": "2020-01-01",
   "price": 100
  },
  {
   "product": 2,
   "date": "2020-01-01",
   "price": 102
  },
  // Additional objects in the array...
]

My desired end result looks like this:

{
 1:{
  "2020-01-01":{
    // Object details for product 1 on January 1st
  }
 },
 2:{
  "2020-01-01":{
    // Object details for product 2 on January 1st
  }
  // More date-specific details for product 2...
 }
}

Even though I attempted the following approach, I'm only managing to capture a single date per product:

pricelist.reduce((obj, item) => {
   obj[item['product']] = {};
   obj[item['date']][item['product']] = item;
   return obj;
}, {});

If anyone can offer guidance on what I might be missing or doing incorrectly here, I would greatly appreciate it.

Answer №1

By ensuring only one item is assigned per date, you can accurately target your assignments.

Your method of substituting product with date in the code does not produce the intended results.

var pricelist = [{ product: 1, date: "2020-01-01", price: 100 }, { product: 2, date: "2020-01-01", price: 102 }, { product: 1, date: "2020-01-02", price: 99 }, { product: 2, date: "2020-01-02", price: 92 }, { product: 1, date: "2020-01-03", price: 101 }, { product: 2, date: "2020-01-03", price: 22 }],
    result = pricelist.reduce((obj, item) => {
        obj[item.product] = obj[item.product] || {};
        obj[item.product][item.date] = item;
        return obj;
    }, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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 could be the reason my script fails to execute during an AJAX refresh?

As I was working on my project's avatar uploader, everything seemed to be going smoothly until this morning when chaos ensued. It was a moment of pure sadness. Initially, selecting a file would prompt the crop tool to appear immediately, and it worke ...

Typescript is having issues with the Foreach function

Can someone explain how I can utilize foreach in this scenario to showcase all the names? exampleData: [{ id: "1", name: "John" }, { id: "2", name: "Jane" }] The following code snippet does not seem to be working: this.exampleData.forEac ...

Tips for displaying errors in React applications

Having trouble troubleshooting React (16.13.0) as I am not receiving any useful errors, just this message: Error: Minified React error #321; visit https://reactjs.org/docs/error-decoder.html?invariant=321 for more info or switch to the non-minified dev en ...

Utilizing various REST API endpoints in Dart

On a single page, I am loading three JSON APIs. However, the process seems to be taking longer than expected to load the content. What are some ways to enhance the speed and efficiency of this process? ...

Utilizing HTML5 Canvas for Shadow Effects with Gradients

Surprisingly, it seems that the canvas API does not support applying gradients to shadows in the way we expect: var grad = ctx.createLinearGradient(fromX, fromY, toX, toY); grad.addColorStop(0, "red"); grad.addColorStop(1, "blue"); ctx.strokeStyle = gra ...

Activate modifications in a distinct column?

I've been exploring a solution to achieve a similar functionality where clicking or hovering on headings in a column brings up corresponding text in another column. My idea is to use list items with a carousel for this purpose, but I'm facing so ...

Create a tree view structure from JSON data using a combination of jQuery and ASP.NET

I am working with asp.net and ajax to create Json data. While attempting to build a tree using the code provided, I encountered issues. On the other hand, Code 2 section works fine when it's static. Please note that I am using the treant.js library. ...

According to npm, the JSON is not valid, but jsonlint.com confirms that it is valid

Here is the json file for package.json that I used npm install on (specifically for the angularfire-seed project on github): { "name": "angularfire-seed", "description": "A starter project for Angular + Firebase with AngularFire", "version": "1.0.0 ...

What is the best way to upload this array into the system's memory?

I recently stored an array by using the code below: NSData *data = [NSKeyedArchiver archivedDataWithRootObject:myArray]; [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"myArray"]; Could you provide the code needed to retrieve this array ba ...

Is there a way for me to display both the right and wrong answers in real-time as users make their selections on my multiple-choice question website? Additionally, can I track the number

I've just implemented the code for my multiple-choice question (MCQ) website. One of the key features I want to include is immediate feedback when a user selects an answer - indicating whether it is correct or incorrect along with showcasing the corre ...

"I'm trying to incorporate react-datepicker into my ReScript application, but I'm struggling to

I am attempting to incorporate an external library like react-datepicker into my project. Below is the code snippet and how I am using it: module DatePicker = { @react.component @module("react-datepicker") external make: () => React.eleme ...

Sending an HTTP post request with form data and various field controls will not be directed to a Java backend

Recently, I've started working with AngularJs and I'm facing an issue with uploading image files along with their labels through a Jax-RS post rest API. My problem is that the control in my AngularJS controller is not entering the Java post API. ...

Encountered an issue when trying to establish the session description: An error occurred while attempting to set the remote answer SDP: Request was made in an inappropriate state

Using Angular JS to Get Room Id/Token from Server Side for WebSocket Connection Code Snippet Used in Application - app.controller("videoCallingController", ["$scope", "$location", "$rootScope", "$localStorage", 'AuthenticationService', "CommonS ...

Is it possible to establish a CSS minimum width that is relative to a different element?

Is it possible to set the min-width of a submenu in CSS to be equal to that of the corresponding link in a navigation menu? I am using LESS for my styling. <ul> <li> <a href="">Item FooBarBaz</a> <ul class="submenu"&g ...

lua update/swap 2D array

I'm facing an issue with my array2d. I am looking to implement a refresh command in my code. The data is stored in data.txt test1:30:1 test2:40:2 Whenever I call the ReadData function, it should populate my Array2d like this : line_data = {{"test1 ...

What could be the reason for the GET request not functioning properly in Node.js?

const express = require('express'); const mongoose = require ("mongoose"); const app = express(); const Student = require('../models/students'); require('dotenv').config(); const PORT = process.env.PORT || 3000; const co ...

notifications failing to load properly on my rails application

I have created a rails application where users can comment on specific tasks. Whenever a new comment is posted on a task, all the users following that project should receive a notification. However, I am facing an issue where my ajax notifications are not ...

Failure to receive a response from ExpressJS jQuery ajax Post request

I am facing an issue with my Ajax post request as I am unable to retrieve any values in the console. Can anyone point out what might be missing here? Node.js app.post('/register',function(req,res) { //console.log(JSON.stringify(req.body)); ...

"Can you provide guidance on binding data in vue.js when there is a dash (-) in the key of the JSON

My JSON data is structured as follows: { "color-1": "#8888", "color-2": "#000" } I am attempting to bind this variable with a style tag for a Vue component. However, my current approach seems to not be functioning as expected. <div v-bind:sty ...

Passing JSON data from NodeJs Express to BackboneJS

Hey there, I'm a bit stuck trying to figure out why my code isn't working as expected. I am attempting to send a simple JSON object to my client using Backbone fetch. It works perfectly fine with the JSON test link, but for some reason it's ...