Generate a collection of items through replication

Develop a function that takes specific input and generates an array of objects with a length of 10 by incrementing the ID of each duplicate object.

The first object in the output array should have "visible" set to true, while all others should have it set to false.


    Input:
    {
        id: 0,
        visible: true,
        width: 200;
        height: 200;
    }

    Output:
    [
        {
            id: 0,
            visible: true,
            width: 200;
            height: 200;
        },
        {
            id: 1,
            visible: false,
            width: 200;
            height: 200;
        },
        {
            id: 2,
            visible: false,
            width: 200;
            height: 200;
        },
        {
            id: 3,
            visible: false,
            width: 200;
            height: 200;
        },
        .
        .
        .
        {
            id: 9,
            visible: false,
            width: 200;
            height: 200;
        }
    ]

Answer №1

Create a 10 element array, fill it with 0 (or any value for iteration), then use the map function to iterate over it and return a copy of the input with the desired id on each loop:

Note: The code snippet has been updated to include logic for the visible property which was missed in the original post.

const input = { id: 0, visible: true, width: 200, height: 200 };

const output = Array(10).fill(0).map((x, id) => ({...input, visible: id === 0, id}));

console.log(output)

Answer №2

If you're looking for assistance, it's important to share your efforts and where you encountered difficulties before asking others to do the work for you.

const example = {
    key: 0,
    display: true,
    length: 200,
    width: 200
}

let examplesArray = [];

for (j = 0; j <= 10; j++) {
    examplesArray.push({
        ...example,
        display: j === 0,
        key: j
    })
}
console.log(examplesArray)

Answer №3

Here is my proposal...

const data = { name: 'John', age: 30, gender: 'male' }

const newData = [];

for (let i=0; i<5; i++) {
  newData.push( Object.assign({}, data, { id: i, age: (data.age + i) }) )
}

console.log(newData);

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 is the purpose of making a "deep copy" when adding this HTML content?

My canvas-like element is constantly changing its contents. I am attempting to execute a function on each change that captures the current content and adds it to another element, creating a history of all changes. window.updateHistory = func ...

Using Javascript to dynamically add rows to a table, however they mysteriously appear and disappear soon

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UserPermisson.aspx.cs" Inherits="TestProjects.UserPermisson" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" ...

Activate the b-form-file function by selecting the b-button

Working with BootstrapVue, I am trying to trigger my b-form-file after clicking on a b-button for style reasons. Additionally, I want the b-form-file to be hidden so it is not visible. I attempted the following approach, but it did not work for me: <b- ...

Leveraging the "dialogclose" event within jQuery Mobile

Is there a way to change an image once it is clicked and change back when the dialog it links to is closed? I found a potential solution on this site, but after modifying it for my needs, it doesn't seem to work. Can anyone help me figure out what I a ...

Data is persisted in the database even when an error occurs

When a user submits their Permanent Account Number (PAN), I check if it already exists in the database. If it does, I receive an error message stating that the PAN number is already registered. However, if I ignore the error and proceed without changing th ...

What steps can I take to trigger a 404 error instead of a cast error?

My route is defined as /mysafe/idofthemodel. When the idofthemodel is not found, it throws a cast error Cast to ObjectId failed for value "something" (type string) at path "_id" for model "modelname". Instead of this error, I ...

Eliminate the unnecessary code repetition in my functions using Typescript

I have 2 specific functions that manipulate arrays within an object. Instead of repeating the same code for each array, I am looking for a way to create reusable functions. Currently, my functions look like this: setLists(): void { if (this.product.ord ...

Generating a collection of items using a pre-existing array of items

Struggling to create an array of objects based on another array of objects. I attempted to use flatMap and then reduce, but encountered an issue when I tried to collect multiple statuses in one object. Below is what I have attempted and the desired result ...

issues with jquery functionality on mobile devices

I'm currently working on a website where I've implemented a jQuery script to dynamically load specific parts of an HTML page with an ID of 'guts' into the main content area. The goal was to keep the menu consistent while only changing t ...

Display current weather conditions with the Open Weather API (featuring weather icons)

Hello everyone, I need some help from the community. I am currently working on a weather app using the openweather API. However, I'm facing an issue with displaying the weather conditions icon for each city. I have stored every icon id in a new array ...

Consolidate various arrays of objects while eliminating duplicate items based on an optional property

Imagine having multiple arrays like these: const arr1 = [ { "id": "1", "type": "sales" }, { "id": "2", "type": "finance" } ] const arr2 = [ { "type": "s ...

Concerns regarding the set-up of the latest React application

My goal is to become proficient in React, so I decided to install Node.js (v 10.16.0 LTS) and run the following commands using Windows Powershell: npx create-react-app my-app cd my-app npm start However, after making changes to the code (such as modifyin ...

Struggling with a peer requirement for grunt@~0.4.0 during the installation of grunt plugins? Here's how to resolve

I recently tried to set up some Grunt plugins such as grunt-contrib-clean and grunt-contrib-watch using the commands npm install grunt-contrib-clean --save-dev and npm install grunt-contrib-watch --save-dev However, I encountered the following warnings: n ...

Utilizing a variable string name for a method in Typescript Vue

My objective is to trigger a different function based on the value of a variable. However, when working in VS Code, I receive an error message that states: 'method' implicitly has a type of 'any' because 'type1Func' and &apos ...

Display or conceal nested divs within ng-repeat loop

I set up a div with sub divs to establish a nested grid system. There are three levels altogether: MainDiv - Always Visible SecondDiv - Display or conceal when MainDiv is clicked on ThirdDiv - Display or conceal when SecondDiv is clicked on <div c ...

Issue encountered while submitting form on JQuery Mobile framework

Currently, I am in the process of developing a small web application utilizing JQuery Mobile and Multi Page architecture. The issue arises on my form as the second page. Upon clicking the submit button, an error message is displayed on my console (error i ...

Using Rails to render a partial containing a form object

I need help with rendering a partial called 'colordata' after selecting a color from a dropdown list using Ajax. Unfortunately, I'm not seeing any changes on the main page and the form is undefined in the colordata partial. This is the sche ...

Limiting Firebase communication to Electron Application

Is there a way to restrict access to a Firebase realtime database or any other database from an Electron application? I understand that you can restrict access by specifying the server your website is hosted on, but since Electron is local, are there any o ...

Utilizing ReactJS for Web Development with Enhanced Data Insights from Google

Utilizing Google Analytics and various tools, I've encountered an issue with the development of ReactJS. My goal was to collect analytics data from my website by using react-helmet to dynamically change the title and the HTML lang parameter based on t ...

Some design elements are present in the interface. The functionality of the data tables is working properly, however, upon reloading the page, the table header shrinks. Interestingly

[![enter image description here][1]][1] This is the JavaScript code along with my footer and header references. The issue I am facing is with the design - initially, it shows a buggy design but when I click on the header, it displays the correct design. & ...