Good evening.

There is an associative array with the function of adding to it:

var usersData = []; var usersObj = {id: i, name: '', email: ''};` function AddUser(name, email, id) { usersData.push({ name: name, email: email, id: i++ }); } 

How can I overwrite the data of one of the elements through the console in this array, if I want to, for example, change the email or name.

  • javascript is a case-sensitive language. UsersData and usersData - 2 different variables - vp_arth

1 answer 1

Judging by the code from the question, the AddUser function will add the usual object to the usersData array and its properties will be accessed via the index of the specific object in the array + the name of the property, and you can change the same name from the console like this:

 usersData[0]['name'] = 'new user name at element 0'; 

or so:

 usersData[0].name = 'new user name at element 0'; 

if you need to change the name in all objects of the array elements:

 function editAll(paramName, paramValue){ for (var j = 0; j < usersData.length; j++) { usersData[j][paramName] = paramValue; }; }; 

I didn’t immediately notice that it’s not necessary to edit everything, but the necessary element, for this you need to come up with a condition by which the necessary element will be determined, for example, editing elements with an even id :

 "use strict"; var i = 0; var usersData = []; for (var k = 0 ; k < 10; k++){ AddUser('name ' + k , 'email ' + k); }; var oldArray = usersData; console.log(oldArray); editAll('name' , 'new name', function(val){ if(val == 0) return false; return !(val % 2); }); console.log(usersData); function AddUser(name, email) { usersData.push({ name: name, email: email, id: i++ }); }; function editAll(paramName, paramValue, f){ for (var j = 0; j < usersData.length ; j++) { if(f(usersData[j].id)) { usersData[j][paramName] = paramValue; }; }; }; 

In this example, as the determinant of the element that needs to be edited, I used the function, but you can also insert a condition directly into editAll with a check of the same id.

  • and if for example I have 50 such elements, how can I iterate over them and edit the element I need? - Imp3l
  • added to the answer a function that does what is necessary, but apparently you should read about arrays, objects, and about working with them - Rostyslav Kuzmovych