The code below comes from jQuery UI Autocomplete:
var projects = [ { value: "jquery", label: "jQuery", desc: "the write less, do more, JavaScript library", icon: "jquery_32x32.png" }, { value: "jquery-ui", label: "jQuery UI", desc: "the official user interface library for jQuery", icon: "jqueryui_32x32.png" }, { value: "sizzlejs", label: "Sizzle JS", desc: "a pure-JavaScript CSS selector engine", icon: "sizzlejs_32x32.png" } ];
For example, I want to change the desc value of jquery-ui. How can I do that?
Additionally, is there a faster way to get the data? I mean give the object a name to fetch its data, just like the object inside an array? So it would be something like jquery-ui.jquery-ui.desc = ....
To change the value of an object in an array:Call the findIndex() method to get the index of the specific object. Access the array at the index and change the property's value using dot notation. The value of the object in the array will get updated in place.
To change the value of an existing property of an object, specify the object name followed by: a dot, the name of the property you wish to change, an equals sign, and the new value you wish to assign.
To change the value of all elements in an array:Use the forEach() method to iterate over the array. The method takes a function that gets invoked with the array element, its index and the array itself. Use the index of the current iteration to change the corresponding array element.
Using the same method, an object's property can be modified by assigning a new value to an existing property. At this point, if we call the object, we will see all of our additions and modifications. Through assignment operation, we can modify the properties and methods of a JavaScript object.
It is quite simple
findIndex
method.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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With