Changing an Element by 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's say we want to change some element of the array. Let the new data be stored in a variable, for example, like this:
let data = {
id: 'IWSpfBPSV3SXgRF87uO74',
prop1: 'value21 !',
prop2: 'value22 !',
prop3: 'value23 !',
};
In the given object, the id matches
the id of the second element of the array, but the values
of the properties are different. In other words,
in data, the id property stores
the id of the array element that
we want to change.
Let's perform this change. To do this,
we will iterate through the array elements with a loop
and, if the id matches the target one, we will
replace the element, and if it doesn't match, we will leave
the element unchanged:
let res = arr.map(elem => {
if (elem.id === data.id) {
return data;
} else {
return elem;
}
});
The code can be shortened by using the ternary operator:
let res = arr.map(elem => elem.id === data.id ? data : elem);
Let a variable store the id of an element
in the array. Create a button that, when clicked,
will change the corresponding
element of the array.