⊗jsSpDtIEA 290 of 294 menu

Adding an Element with id in JavaScript

Let the variable arr contain an array of objects:

let arr = [ { id: 'GYi9GauC4gBF1e2SixDvu', prop1: 'value11', prop2: 'value12', prop3: 'value13', }, { id: 'IWSpfBPSV3SXgRF87uO74', prop1: 'value21', prop2: 'value22', prop3: 'value23', }, { id: 'JAmjRlfQT8rLTm5tG2m1L', prop1: 'value31', prop2: 'value32', prop3: 'value33', }, ];

Let another variable store the object that we want to make a new element of our array:

let newElem = { id: 'GMNCZnFT4rbBP6cirA0Ha', prop1: 'value41', prop2: 'value42', prop3: 'value43', };

Let's consider the immutable addition of such an element. Let's create a copy of the array and add a new element to it:

let copy = Object.assign([], arr); copy.push(newElem); let res = copy;

Or use destructuring:

let res = [...arr, newElem];

Given an array of objects. Create a button that, when clicked, will add a new element to it. Let the id be generated by a function.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline