⊗jsSpDtIPCh 293 of 294 menu

Modifying a Single Property by id in JavaScript

You may need to modify not the entire object, but a specific property. Let's see how it's done.

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 the variables contain the element's id, the property name to change, and the new property value:

let id = 'IWSpfBPSV3SXgRF87uO74'; let prop = 'prop1'; let value = '!!!';

To solve the problem, it is convenient to use destructuring and computed property names:

let res = arr.map(elem => { if (elem.id === id) { return {...elem, [prop]: value}; } else { return elem; } });

The following variables are given:

let id = 'JAmjRlfQT8rLTm5tG2m1L'; let prop = 'prop2';

Create a button that, when clicked, will take the array element with the specified id, will take the property with the specified name in it, and the symbol '!' will be appended to the end of this property's value.

Let two variables with property names be given:

let id = 'JAmjRlfQT8rLTm5tG2m1L'; let prop1 = 'prop2'; let prop2 = 'prop3';

Modify the previous task so that on click, the changes are performed for two specified properties at once.

Redo the solution provided in the theory by copying the object using Object.assign.

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