I have an array of objects like this (from jQuery UI Autocomplete):
var projects = [
{ value: "jquery", label: "jQuery", desc: "...", icon: "..." },
{ value: "jquery-ui", label: "jQuery UI", desc: "...", icon: "..." },
{ value: "sizzlejs", label: "Sizzle JS", desc: "...", icon: "..." }
];
I’d like to update a specific object in the array. For example, change the desc of the one where value === "jquery-ui"
. What’s the best way to update an object in array JavaScript?
Also, is there a smarter or faster way to fetch this object, like assigning names or keys to make direct access easier (instead of looping each time)?
Hey! you can use Array.prototype.find()
to get the object reference directly and then update its properties. Super handy when you’re collaborating and want clear, readable logic:
const item = projects.find(p => p.value === "jquery-ui");
if (item) {
item.desc = "Updated description here!";
}
This approach keeps it clean and avoids mutating anything unnecessarily, your teammates will appreciate how maintainable it is.
If you’re accessing these items often and by value, it might be worth transforming the array into an object map. That way, you avoid iteration:
const projectMap = {
"jquery": { ... },
"jquery-ui": { ... },
"sizzlejs": { ... }
};
projectMap["jquery-ui"].desc = "Updated using key!";
This makes it easy for everyone on the team to access and update values quickly, just like you hinted with jquery-ui.desc.
If you want to stay immutable like in collaborative environments where state is shared (e.g., React or Redux) use .map() to create an updated copy:
const updatedProjects = projects.map(project =>
project.value === "jquery-ui"
? { ...project, desc: "Updated in a new array!" }
: project
);
This helps avoid side effects and works well when you and your team want safe, predictable updates without modifying the original array.