How to change value of object which is inside an array using JavaScript or jQuery?
It is quite simple
- Find the index of the object using
findIndex
method. - Store the index in variable.
- Do a simple update like this:
yourArray[indexThatyouFind]
//Initailize array of objects.let myArray = [ {id: 0, name: "Jhon"}, {id: 1, name: "Sara"}, {id: 2, name: "Domnic"}, {id: 3, name: "Bravo"}], //Find index of specific object using findIndex method. objIndex = myArray.findIndex((obj => obj.id == 1));//Log object to Console.console.log("Before update: ", myArray[objIndex])//Update object's name property.myArray[objIndex].name = "Laila"//Log object to console again.console.log("After update: ", myArray[objIndex])
You have to search in the array like:
function changeDesc( value, desc ) { for (var i in projects) { if (projects[i].value == value) { projects[i].desc = desc; break; //Stop this loop, we found it! } }}
and use it like
var projects = [ ... ];changeDesc ( 'jquery-ui', 'new description' );
UPDATE:
To get it faster:
var projects = { jqueryUi : { value: 'lol1', desc: 'lol2' }};projects.jqueryUi.desc = 'new string';
(In according to Frédéric's comment you shouldn't use hyphen in the object key, or you should use "jquery-ui" and projects["jquery-ui"] notation.)
The best solution, thanks to ES6.
This returns a new array with a replaced description for the object that contains a value equal to "jquery-ui".
const newProjects = projects.map(p => p.value === 'jquery-ui' ? { ...p, desc: 'new description' } : p);