Dynamically incorporate new items into an array containing multiple objects

Is there a way to dynamically add objects to an array of objects based on a value? Let's say we have the following array of objects:

[
    {category:A, num:5}, 
    {category:B, num:2}
] 

I would like to create another array where objects are repeated based on the 'num' value (5 times for category A and 2 times for category B), like this:

[
    {category:A, num:5, repeated:1},
    {category:A, num:5, repeated:2},
    {category:A, num:5, repeated:3},
    {category:A, num:5, repeated:4},
    {category:A, num:5, repeated:5},
    {category:B, num:2, repeated:1}, 
    {category:B, num:2, repeated:2}
]

I've attempted using map, forEach, and for loops but haven't had success. I'm new to JavaScript and would appreciate any help or guidance!

Answer №1

To achieve this, you can utilize a clever mix of flatMap and map:

let data = [
    {type: "X", quantity: 8}, 
    {type: "Y", quantity: 3}
] ;

let output = data.flatMap(item => [...new Array(item.quantity)].map( (val,index) => ({
    type:item.type,
    quantity: item.quantity,
    indexValue: index+1
})));
console.log(output);

Answer №2

To achieve this, you can utilize the flatMap method in JavaScript -

const repeatItems = ({ times = 0, ...rest }) =>
  times === 0
    ? []
    : [ ...repeatItems({ ...rest, times: times - 1 }), { ...rest, times, repeatedTimes: times } ]

const data = 
  [ { type: "X", times: 4}, { type: "Y", times: 3 } ]
  
const result =
  data.flatMap(repeatItems)
  
console.log(result)

Result -

[
  { type: "X", times: 1, repeatedTimes: 1 },
  { type: "X", times: 2, repeatedTimes: 2 },
  { type: "X", times: 3, repeatedTimes: 3 },
  { type: "X", times: 4, repeatedTimes: 4 },
  { type: "Y", times: 1, repeatedTimes: 1 },
  { type: "Y", times: 2, repeatedTimes: 2 },
  { type: "Y", times: 3, repeatedTimes: 3 }
]

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

Issue Installing Npm Package (detected 23 security vulnerabilities)

My attempt to install the package resulted in an error message. How can I resolve this issue? ...

Using a jQuery function to pass a value through $_GET parameters

I am trying to pass a dropdown value using $_GET with the help of a jQuery function This is the code I have written: <div class="span2 text-right"> <label class="f-s15">Choose Exam to take:</label> </div> <div class="span3" ...

Leveraging the power of JavaScript to retrieve data from PHP/MySQL

Considering creating an Android app using Appcelerators Titanium application and have a question. The website for the app is built with PHP/MySQL, and I'm curious if it's possible to dynamically pull data from the database using JavaScript in Tit ...

Changing a JSON string array into an NSArray in Swift

When I receive a response, it looks something like this in some key: "abc" : "[{\"ischeck\":true,\"type\":\"Some type\"},{\"ischeck\":false,\"type\":\"other type\"}]"]" To convert this into a no ...

Error: The requested collection# cannot be found in the Node.js Express routing system

Recently, I have started learning nodejs and implemented a simple API that allows users to log in with passport and then redirects them to the /collections route. While this part is functioning correctly, I am encountering issues with POST requests which a ...

What is the best way to visualize the PerspectiveCamera in three.js?

Upon diving into the tutorial on drawing lines in three.js documentation, I came across some intriguing code snippets: All seemed well and good with the code. <html> <head> <meta charset="utf-8"> <title&g ...

When working with Visual Studio and a shared TypeScript library, you may encounter the error message TS6059 stating that the file is not under the 'rootDir'. The 'rootDir' is expected to contain all source files

In our current setup with Visual Studio 2017, we are working on two separate web projects that need to share some React components built with TypeScript. In addition, there are common JavaScript and CSS files that need to be shared. To achieve this, we hav ...

The `$scope variable fails to update in another controller`

I am currently facing an issue with updating a value on my view. Let me walk you through my code along with a brief explanation of the situation. The code may look messy as I have been experimenting with different combinations lately. The controller in qu ...

Variable remains unchanged by method

I am currently working on an app that utilizes the user's webcam. In case navigator.getUserMedia fails, I need to change the error variable to display the appropriate error message instead of the stream output. Since I am new to Vue, please bear with ...

Upon redirecting to a new page following the loading of a previous page

At the moment, I have a webpage where filling out a text box and clicking a button redirects you to another page. This page must be loaded because it updates and displays XML data (this aspect cannot be changed). However, my goal is to either redirect th ...

Step by step guide on uploading files using Vue.js and Express.js

Hello there, I am new to Vuejs and Express and I'm looking to practice my skills. Currently, I am attempting to build a User Profile with an image upload feature using Vuejs and ExpressJs but unfortunately, none of the files or text are uploading as ...

Exploring the integration of Formik with Material-UI's select field - A step-by

Trying to implement Formik with Material-UI's Textfield component using the select attribute. Every time I change the option, it shows this warning: Material-UI: You have provided an out-of-range value null for the select (name="subIndicatorId& ...

Understanding Aspect Ratios in CSS for Div Containers and their Components

I am crafting an HTML5 game without the use of canvas and aiming to maintain a 16:9 aspect ratio within my div. Thanks to javascript, achieving this is straightforward and it functions flawlessly. However, the elements inside the div occasionally appear to ...

What are the steps to synchronously retrieve data from an API in Node.js?

Short version: How can I use ES6 fetch to download data synchronously? I am currently working on a script in Node that requires downloading data from an API continuously until there is no more data left to be downloaded. For example, the API endpoint cont ...

Validating Custom Checkout Fields in Woocommerce Version 3

In my checkout process for a bookings website, I have implemented custom input fields that are displayed based on the number of participants. These fields are properly sanitized and shown in the admin panel in the correct order. The input fields are mand ...

jquery causing issues with browser functionality

I'm new to working with JQuery and currently in the process of deconstructing a code snippet I found online. The code functions perfectly fine on JSFiddle: JSFIDDLE. However, when attempting to run it in a browser, the section that should appear upon ...

Conceal the Submit button upon completing the form submission using the load method

When creating a form and sending a request to another page, I use the following code: $(document).ready(function() { $("#send").click(function() { var text = $("#text").val(); var email = $("#email").val(); $("#exp").load("sendmail.php",{text: ...

Repairing the Left-sided Popup Leaflet

Can someone help me with fixing the positioning of the Popup to the left of the map? Currently, it does not stay aligned to the left edge when moving the map. I tried using position: fixed in my styling, and while everything looks good when zooming, it br ...

Discovering Consecutive Matching Positions in an Array

I am trying to find the first location (or set of locations) in an array that is distinctly different from the initial location. The difference is determined based on a function calculating their distance. Here's an example array: [ {lat: 45, lng: ...

Utilizing the powerful combination of Vue.js and Laravel for seamless invoice editing in the backend

MODIFIED : These arrays are retrieved from invoice_items where products match the invoice ID [ { "id": 27, "invoice_id": 14, "product_id": 1, "unit_price": 200, "prod ...