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

AngularJS: How service query data is perceived as an object and therefore cannot be utilized by Angular

When retrieving data from my PHP server page in the factory service, I encountered two different scenarios: If I call a function that returns an array and then use json_encode($data); at the end, Angular throws a resource misconfiguration error due to ...

Accessing information from Firebase and displaying it within an Angular Controller

As a newcomer to the latest Firebase SDK (with some experience using angularfire), I set out to retrieve data and display it using Angular. This is my progress so far: var app = angular.module('dApp',[]); app.controller('listingControler&a ...

React version 18.2.0 and Next.js version 13 faced an issue with hydration failure due to the initial user interface not matching. This problem

Upon opening the page, I encounter an error when focusing on the input element right away. However, if I wait a few seconds before focusing on the input element, the error does not occur. Unfortunately, I have been unable to resolve this issue. Interesting ...

Converting a JavaScript array to JSON format

I'm struggling with JavaScript and need some help. I have two arrays that I want to convert into a data series, but I'm not sure how. Here are the arrays: colors = ['red', 'green', 'blue']; values = [20, 50, 10 ...

What are some ways to track the loading progress of a JSON file retrieved through an Axios call?

To track progress accurately, I am contemplating implementing the following steps while making an axios call: Retrieve file size during the json file request Determine the percentage of downloaded file size from the network tab Currently, I only have a ...

Display or conceal fields depending on custom object specifications

I am attempting to centralize my show/hide functionality for fields in one object (like vm.foo) that contains key-value pairs. For example, I could add another pair like 1502: true to hide a field with the key 1502. Is there a way to pass variables from t ...

Refreshing Angular Page

I'm looking for a way to reset my Angular page back to its original state with just one button click. I attempted to use the angular.copy method, but encountered an error. I have various scope and controller variables that I don't want to reset i ...

Innovative approach for showcasing JSON array using checkboxes

I have created a multidimensional array using JSON. However, now I am facing the challenge of organizing groups of checkboxes in a visually appealing manner, such as separating them with horizontal bars or placing them into tables. Here is an example of t ...

What are the advantages of incorporating JSON for retrieving data from MySQL?

So I have developed a website that retrieves data from a MySQL database using PHP, and then transforms it into JSON format for use with JavaScript. This process can be broken down into 5 steps: Query -> PDO Statement -> PHP Array -> JSON Strings -> JS ...

Utilizing functions for object creation in JavaScript

Having trouble with creating a function that automatically generates an object and then alerts its properties. Can't seem to get the alerts when I click the button. Any assistance would be appreciated. <html> <head> <s ...

Loop through the properties of a JsonObject

My goal is to use Gson to iterate through the large wrapping JsonObject. I want to extract an ArrayList containing all three-digit code integers from the inner "unterfeld" objects. This should be straightforward once I can successfully iterate through the ...

Retrieving information from an API and transferring it to the state in a React component

I am currently working on a random quote generator project, and I'm facing some difficulties in passing the API data to my state and also accessing it in the QuoteComponent through props. Despite following all the correct procedures, whenever I try to ...

What is the best method for implementing click functionality to elements that share a common class using only pure JavaScript

I am struggling to figure out how to select specific elements with the same classes using only pure JavaScript (no jQuery). For example: <div class="item"> <div class="divInside"></div> </div> <div class= ...

Tips for sending a form and showing results without the need to refresh the page

I am currently working on developing a basic calculator that takes a user input number and displays the calculated output without redirecting or reloading the page. However, since I have no experience with JavaScript (js) and Ajax, I am seeking assistance ...

Can you create a while loop that continuously asks for user input, stores the responses, and then makes them accessible in an array?

When developing a Yeoman generator, the necessary dependencies can be found at https://github.com/sboudrias/mem-fs-editor#copytplfrom-to-context-settings and https://github.com/SBoudrias/Inquirer.js/. The main goal is to prompt the user with a question an ...

Implementing multiple condition-based filtering in React Native for arrays

I am looking to apply multiple filters to an array based on certain conditions defined by toggling switches. The issue arises when toggling two or more switches simultaneously, resulting in an empty array. My goal is to retrieve an array containing the tru ...

What is the correct way to interpret the URL of attachments in messages?

I'm trying to create a feature where, when someone sends an image or a link of an image (like with Imgur), the attachment's URL gets logged in a specific channel. I attempted to achieve this using if(message.attachments.length > 0 || message. ...

Create a vibrant PNG image background that changes dynamically based on the dominant color of the

Is it possible to dynamically set the background color of a PNG image, either white or black, based on the dominant color in the image? For example, this image should have a dark background: https://i.stack.imgur.com/cerjn.png And this one should have a ...

Scrolling with Jquery window.scrollTo results in the page becoming unresponsive

I'm currently revamping a website that features a header with 100% screen height, but I need it to shrink down to 0px when a user starts scrolling. The issue I'm facing is that once the header shrinks to 0px, the page content ends up slightly abo ...

How can you append an object with a defined key to an array in Vue?

Currently developing a vue-application that includes a component for managing driving licenses. Here is an overview of my data setup: data() { return { custom_licenses: [], basic_licenses: [] } } Within my methods, I have the following l ...