Creating an array of objects in Javascript by setting two different values as a range

Given an array of objects structured as follows:

[{value: "a", start: 1950, end: 1954, description: "aaa"},
{value: "b", start: 1953, end: 1956, description: "bbb"},
{value: "c", start: 1960, end: 1962, description: "ccc"}]

How can I expand the array to achieve the desired output using javascript? I aim to expand each object by including a new key year for every year between the given start and end.

[{value: "a", year: 1950, start: 1950, end: 1954, description: "aaa"},
{value: "a", year: 1951, start: 1950, end: 1954, description: "aaa"},
{value: "a", year: 1952, start: 1950, end: 1954, description: "aaa"},
{value: "a", year: 1953, start: 1950, end: 1954, description: "aaa"},
{value: "a", year: 1954, start: 1950, end: 1954, description: "aaa"},
{value: "b", year: 1953 ,start: 1953, end: 1956, description: "bbb"},
{value: "b", year: 1954, start: 1953, end: 1956, description: "bbb"},
{value: "b", year: 1955, start: 1953, end: 1956, description: "bbb"},
{value: "b", year: 1956, start: 1953, end: 1956, description: "bbb"},
{value: "c", year: 1960, start: 1960, end: 1962, description: "ccc"},
{value: "c", year: 1961, start: 1960, end: 1962, description: "ccc"},
{value: "c", year: 1962, start: 1960, end: 1962, description: "ccc"}]

I assume I need to use a for loop to iterate over the elements but I'm struggling with incorporating the start and end values from each original value object.

Answer №1

To achieve your desired outcome, consider using the combination of flatMap() along with Array.from().

const data = [
  {value: "x", start: 1990, end: 1994, description: "xxx"},
  {value: "y", start: 1993, end: 1996, description: "yyy"},
  {value: "z", start: 2000, end: 2002, description: "zzz"}
];

const result = data.flatMap(({value, start, end, description}) => {
  return Array.from({length: end - start + 1}, (_, i) => start + i)
              .map(year => ({value, year, start, end, description}));
});

console.log(result);

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

I am looking to update the background color of the material UI helper text

In the image below, you can see that my background color is gray and my text field color is white. When an error is shown, the text field's white color extends and the password error message doesn't look good. I want the text field to remain whit ...

Using react-big-calendar exclusively for the month view

I need help customizing react-big-calendar to only show the month view and trigger a function when a date is selected. I want to remove all other functionalities related to week, day, agenda, and time display. Essentially, I just want to display the month- ...

Tips for adjusting the color of boxes within a grid

I've built a grid containing multiple boxes, each identified with an id of box + i. However, I'm encountering difficulties when attempting to implement an on-click function to change the color of each box. Below is the code snippet in question: f ...

The jquery and operator fails to function

I am encountering an issue with the code snippet below. The functionality involves a button that toggles a div. Within this toggle div, there are several other divs and elements. $(function () { $('#btn').click(function (e) { e.preve ...

The background image shifts dynamically with a parallax effect as the page is scrolled

I need help solving a parallax issue that I'm currently facing. On my webpage, I have a background image positioned at the top with a parallax effect achieved through background-position: fixed. However, I now require the image to scroll along with t ...

Error encountered when attempting to reinitialize DataTable while iterating through multiple tables and searching within tabs

Currently, I am utilizing DataTable to display 3 separate tables with the help of tabs, along with a search function. However, every time I load the page, I encounter a reinitialization error. Here is the snippet of my code: _datatables.forEa ...

Converting data into a multidimensional array in AngularJS: A comprehensive guide

Struggling to convert a JSON array into a multidimensional array, looking for some guidance. I attempted using _.groupBy in underscore.js, but it's not proving successful with the nested array. If there is any way to convert from the given data [{ ...

Change your favicon dynamically based on the user's online or offline status using Vue

I am currently working on setting up different icons to display when my browser is online (normal logo) and offline (greyed out logo). With Vue JS, I am able to detect the online and offline states, as well as set different favicons accordingly. However, t ...

The CSS transition duration is not being applied properly on the initial transition effect

Looking to create a dynamic set of sliding divs that can be triggered with the press of a button. Each div will contain a thumbnail image and accompanying text. The goal is to enable the user to navigate through the content by clicking the left or right bu ...

Transferring hyperlink text to a different page using Express JS

I'm currently dealing with a coding issue where I need to pass a link text within a hyperlink to another page. The web application is built using Express. On one of the pages, there's a dropdown list containing this hyperlink: <a class=" ...

Setting up gulp-typescript for Angular 2: A comprehensive guide

Right now I am utilizing the tsc compiler with the watch flag in the command prompt. It functions correctly, loading all definition files and successfully compiling each angular2 file. However, it is quite cumbersome to use via the shell window. My object ...

Is there a way to directly display all the content in pagination format without a print preview option?

I have been tasked with implementing a feature that involves displaying content using pagination and allowing users to print all the content at once with a single click on a print button. However, I am currently experiencing an issue where clicking the pri ...

Display all event date markers, even if some dates are missing

Using the FullCalendar plugin has been a great experience for me. I have managed to successfully read data from a JSON object with the following code: function press1() { var employees = { events: [] }; ...

Transforming ASP.NET MVC IEnumerable view model into a JSON array of elements

My goal is to develop a dynamic calendar in ASP.NET MVC that pulls event data from a database to populate it. Right now, the calendar is set up to read a json array of objects, but I am facing an issue with converting my ViewModel data into a format that t ...

Is there a way to launch only a single popup window?

Recently, I came across this piece of Javascript code which is causing me some trouble: function call() { popup = window.open('http://www.google.co.in'); setTimeout(wait, 5000); } function caller() { setInterval(call, 1000); } func ...

How come the mongoose ref feature is not functioning properly for me when I attempt to reference objects from a different schema?

I'm having trouble accessing the attributes of a store's address, as I keep getting 'undefined'. It seems that the address is only an id, even though I set up a 'ref' in the address schema. What could be causing this issue? H ...

Difficulty in transmitting two boolean values using ajax and setTimeout()

I am working on two functions that are supposed to send either 0 or 1 to a PHP page using AJAX. When a key is pressed on the keyboard, the function that sends 1 should start, followed by the second function that sends 0 three seconds later using setTimeout ...

How can a controller configure an AngularJS provider by passing options?

How can I pass configuration options to a provider from a controller? Below is an example of how to pass options/configurations to a provider from the controller: provider.js file: app.provider('contactProvider', function() { this.name ...

Having trouble with the tooltip feature in Bootstrap?

I've searched high and low, including on this site! I've experimented with all sorts of code, but nothing seems to make the tooltips function in BootStrap. It's beginning to really frustrate me!! Does anyone happen to have the working js co ...

The Belongs_to association found in ActiveModel::Serializer eradicates the need for a root element in

Currently, I am working on developing an API using Rails. After recently watching the RailsCast episode discussing ActiveModel::Serializer, I became intrigued and decided to experiment with it. Here is a brief overview of my existing models: class Club & ...