Typescript mapping data structure

Currently, I am facing the challenge of mapping complex models.

  • My data consists of an array of Carts with attributes such as id and name.
  • In addition, there is a dictionary where each key represents a type and its corresponding value includes different products.

For visualization purposes, I have included a sample output at the bottom of this page.

Although I have made some progress in my attempt, I am currently stuck on how to effectively filter the data.

carts.forEach(cart => {
    const productList = cart.products; //list of products

    Object.entries(content.data).forEach(([key, values]) => {
      const sizeList = values.map(x => x.sizeList); //list of size
      // i am stuck here
    });
  });

Answer №1

const getProductsWithSizes = (products = [], info = {}) => {
  // create a Map with productId-sizeId as key, and size name as value
  const productSizeNameMap = 
    Object.values(info)
    .flat()
    .reduce((map, { productId, sizeList = [] }) => {
      sizeList.forEach(({ sizeId, name }) =>
        map.set(`${productId}-${sizeId}`, name)
      );
      return map;
    }, new Map);
  // return updated product list with names based on productSizeNameMap
  return products.map(({ id, title, sizes = [] }) => ({
    id: id,
    title: title,
    availableSizes: sizes.map(({ id, size, quantity, availability }) => ({
      id, quantity, availability, name: productSizeNameMap.get(`${id}-${size}`)
    }))
  }));
}

const 
  products = [
    {
      id: 500,
      title: "Product One",
      sizes: [ { id: 1, size: 10, quantity: 1, availability: true }, { id: 2, size: 13, quantity: 10, availability: true } ]
    }
  ],
  info = {
    "Drinks": [
      { productId: 1, sizeList: [ { sizeId: 10, name: "100ml beer" }, { sizeId: 9, name: "200ml beer" } ]
      }
    ],
    "Food": [
      {
        productId: 2,
        sizeList: [ { sizeId: 12, name: "6 wings" }, { sizeId: 13, name: "12 wings" } ]
      }
    ]
};

console.log( getProductsWithSizes(products, info) );

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

Ajax - Trouble with Updating DIV Content

As a beginner in AJAX, I am encountering difficulties creating a simple AJAX program. My goal is to have a button that, when clicked, changes the text of the div below it. Despite numerous attempts, I have not been able to identify the issue. Below is the ...

Is there a way to nest arrays within arrays in JavaScript?

Array ( [0] => Array ( [contactId] => 5 [companyId] => 54 [personName] => Awais [contactNo] => 0321-1111111 [contactType] => Partner ) ) data[0].personName I ...

Unexpected token encountered when using JSON.parse()

I'm encountering an issue where trying to use JSON.parse() on a specific string is resulting in an unexpected token error. It seems to be having trouble with the 'maker' part of the data. Any insight on this issue would be greatly appreciate ...

Save the output to the server's file

Looking for a straightforward way to output the results of a json query in a more structured format. I currently have a file that fetches statistics from a json query and displays it using document.write. Now, I need these results to be stored in a csv or ...

Is it feasible to retrieve an object from AWS S3 in Blob format using AWS SDK for JavaScript V3?

Currently, I am working on a project utilizing Next.js and I am facing the task of uploading photos to a Bucket S3. In order to stay up-to-date with the latest technology, I have chosen to utilize the latest version (3) of AWS SDK for JavaScript. After se ...

Here is a way to return a 400 response in `express.js` when the JSON request body is invalid

How can I make my application send a response with status code 400 instead of throwing an error if the request body contains invalid JSON? import express from 'express' app.use(express.urlencoded({ extended: false })) app.use(express.json()) ...

Smooth scrolling in JavaScript can lead to unexpected jumps when using scroll-margin-top

I am currently working on implementing smooth scrolling into my website using JavaScript. However, I have run into a problem with CSS property scroll-margin-top causing a sudden jump at the end. The CSS I am using for scroll margins looks like this: class ...

Ways to access PromiseValue in XMLHttpRequest with JSON

Is there a way to access an array that is within the PromiseValue instead of receiving Promise {<pending>} When I use .then(data => console.log(data)), I can see the array in the console log. However, my requirement is to display this array on an ...

obtain the text content from HTML response in Node.js

In my current situation, I am facing a challenge in extracting the values from the given HTML text and storing them in separate variables. I have experimented with Cheerio library, but unfortunately, it did not yield the desired results. The provided HTML ...

Comparing ngrx and redux for managing state in stateless components

Exploring ngrx/angular 8 for the first time, I'm curious to know if the angular approach of using an observable to bind a state value to the this context still allows a component to remain presentational and stateless. In the realm of angular/ngrx, c ...

What is the method for retrieving a property from an object contained within an array that is assigned to a property of another object?

How can I retrieve the name property from the subjects array within a course object? The database in use is mongodb. Modifying the course model is not an option. The course model : const mongoose = require('mongoose'); const Schema = mongoose. ...

When encountering issues with the select element, such as when it is combined with AJAX or Bootstrap,

When attempting to use a foreach loop within the <select><option> ... </option></select> element with jquery + ajax, I encountered an issue where no values were displayed. Although there were no errors when reviewing the console lo ...

underscore's _.each() method for callback functions

I've been struggling with implementing my custom _.each() function within another function and keep encountering the issue of getting "undefined" returned. My goal is to utilize _.each() to apply a test function to an array. Despite being aware that t ...

Tips for delaying the evaluation of an <input> field?

I am interested in analyzing the content of an <input> field when there is no activity from the user. One simple example I have considered is counting the number of characters, but the actual analysis process is very resource-intensive. To optimize ...

Exploring the differences between server-side rendering and client-side rendering in Express using Pug

I find myself in a state of confusion when it comes to distinguishing between what is considered client-side and server-side. Currently, as I develop a website using Pug for my HTML pages without any external files being loaded into the client's brows ...

Is it possible to apply (max / min) to a mongoose string?

Is it possible to limit the maximum string length to 5 characters using this method? Or is this functionality only available for numbers? someString: { type: String, max: 5 }, Thank you! ...

Execute JavaScript code once the XMLHttpRequest has completed execution

I'm facing an issue where the JavaScript code is executing faster than the XMLHttpRequest. I am hesitant to resolve it using: setTimeout(function() {}, 100); Below is a snippet of my code: function change_country(id) { if (window.XMLHttpReques ...

What are some ways I can efficiently download large attachments without disrupting the user's experience?

I'm encountering some challenges with handling large attachments in my project. Initially, I had this link code: <a :download="scope.row.name" :href="`data:${scope.row.type};base64,${scope.row.contentBytes}`">download</a& ...

looping through the multi-dimensional array using v-for

Interested in using v-for and I have encountered a scenario with an object structure as seen here: https://i.sstatic.net/wNguk.png Upon inspecting the dev console, the object looks similar to this: https://i.sstatic.net/jyqth.png My query is about how to ...

Ways to achieve 8 columns in a single row using Javascript and Bootstrap

Recently, I created a simple function for searching movies and manipulating them in the DOM. The issue arises when a movie name is entered and the API response returns around 20-30 recommendations. I wanted to display this fetched data in 8 columns per row ...