How to change the value of an object inside an array using JavaScript or jQuery?

The following is the jQuery UI Autocomplete code:

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 value of desc jquery-ui . How can i do this?

Also, is there a faster way to get data? I mean giving the object a name to retrieve its data, just like the object inside the array? So that would be like jquery-ui.jquery-ui.desc = ....

+141
javascript jquery arrays
Jan 14 '11 at 9:59 a.m.
source share
18 answers

You need to search in an array, for example:

 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 make it faster:

 var projects = { jqueryUi : { value: 'lol1', desc: 'lol2' } }; projects.jqueryUi.desc = 'new string'; 

(According to Frederick's comment, you should not use a hyphen in an object key, or you should use the notation "jquery-ui" and projects ["jquery-ui"].)

+100
Jan 14 '11 at 10:05
source share

It's pretty simple

  • Find the index of the object using the findIndex method.
  • Store index in a variable.
  • Do the following next update: 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 name property. myArray[objIndex].name = "Laila" //Log object to console again. console.log("After update: ", myArray[objIndex]) 
+168
Jan 30 '17 at 2:43 on
source share

You can use $. each () to iterate through the array and search for the object of interest to you:

 $.each(projects, function() { if (this.value == "jquery-ui") { this.desc = "Your new description"; } }); 
+34
Jan 14 2018-11-11T00:
source share

ES6 by the way, without mutating the original data.

 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" }]; //find the index of object from array that you want to update const objIndex = projects.findIndex(obj => obj.value === 'jquery-ui'); // make new object of updated object. const updatedObj = { ...projects[objIndex], desc: 'updated desc value'}; // make final new array of objects by combining updated object. const updatedProjects = [ ...projects.slice(0, objIndex), updatedObj, ...projects.slice(objIndex + 1), ]; console.log("original data=", projects); console.log("updated data=", updatedProjects); 
+33
May 24 '18 at 8:03
source share

Better 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 ); 
+24
Aug 07 '18 at 2:59
source share

This can easily be done using the underscore / lodash library:

  _.chain(projects) .find({value:"jquery-ui"}) .merge({desc: "new desc"}); 

Documents:
https://lodash.com/docs#find
https://lodash.com/docs#merge

+17
Mar 15 '16 at 11:31
source share

you can use .find, so in your example

  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" } ]; let project = projects.find((p) => { return p.value === 'jquery-ui'; }); project.desc = 'your value' 
+12
Jul 19 '17 at 15:11
source share

you need to know the index of the object you are changing. then its pretty simple

 projects[1].desc= "new string"; 
+11
Jan 14 2018-11-11T00:
source share

 // using higher-order functions to avoiding mutation 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" } ]; // using higher-order functions to avoiding mutation index = projects.findIndex(x => x.value === 'jquery-ui'); [... projects.slice(0,index), {'x': 'xxxx'}, ...projects.slice(index + 1, projects.length)]; 
+3
Sep 07 '17 at 15:11
source share

Using a map is the best solution without using additional libraries. (Using ES6)

 const state = [ { userId: 1, id: 100, title: "delectus aut autem", completed: false }, { userId: 1, id: 101, title: "quis ut nam facilis et officia qui", completed: false }, { userId: 1, id: 102, title: "fugiat veniam minus", completed: false }, { userId: 1, id: 103, title: "et porro tempora", completed: true }] const newState = state.map(obj => obj.id === "101" ? { ...obj, completed: true } : obj ); 
+3
Sep 03 '19 at 20:44
source share

I think it’s better

 const index = projects.findIndex(project => project.value==='jquery-ui'); projects[index].desc = "updated desc"; 
+2
Feb 06 '19 at 12:16
source share

You can use the map function -

 const answers = this.state.answers.map(answer => { if(answer.id === id) return { id: id, value: e.target.value } return answer }) this.setState({ answers: answers }) 
+2
Jul 23 '19 at 10:30
source share

Try this code. it uses jQuery grep function

 array = $.grep(array, function (a) { if (a.Id == id) { a.Value= newValue; } return a; }); 
0
Oct 17 '16 at 16:41
source share

We can also use the array mapping function to modify the array object using Javascript.

 function changeDesc(value, desc){ projects.map((project) => project.value == value ? project.desc = desc : null) } changeDesc('jquery', 'new description') 
0
Jul 27 '17 at 4:43 on
source share

First find the index:

 function getIndex(array, key, value) { var found = false; var i = 0; while (i<array.length && !found) { if (array[i][key]==value) { found = true; return i; } i++; } } 

Then:

 console.log(getIndex($scope.rides, "_id", id)); 

Then do what you want with this index, for example:

$ scope [returnindex] .someKey = "someValue";

Note: please do not use for, since for will check all the documents in the array, use while with a cork, so it will stop as soon as it is found, thereby speeding up the code.

0
Nov 21 '17 at 7:05
source share

Here I use angular JS. In JavaScript, you can use to loop to find.

  if($scope.bechval>0 &&$scope.bechval!=undefined) { angular.forEach($scope.model.benhmarkghamlest, function (val, key) { $scope.model.benhmarkghamlest[key].bechval = $scope.bechval; }); } else { alert("Please sepecify Bechmark value"); } 
0
Dec 14 '18 at 9:27
source share

To update multiple items using matches:

 _.chain(projects).map(item => { item.desc = item.value === "jquery-ui" ? "new desc" : item.desc; return item; }) 
-one
May 04 '16 at 23:12
source share

This is my answer to the problem. My underline version was 1.7, so I could not use .findIndex .

So I manually got the index of the item and replaced it. Here is the code for the same.

  var students = [ {id:1,fName:"Ajay", lName:"Singh", age:20, sex:"M" }, {id:2,fName:"Raj", lName:"Sharma", age:21, sex:"M" }, {id:3,fName:"Amar", lName:"Verma", age:22, sex:"M" }, {id:4,fName:"Shiv", lName:"Singh", age:22, sex:"M" } ] 

The method below will replace the student with id:4 with a lot of attributes in the object

 function updateStudent(id) { var indexOfRequiredStudent = -1; _.each(students,function(student,index) { if(student.id === id) { indexOfRequiredStudent = index; return; }}); students[indexOfRequiredStudent] = _.extend(students[indexOfRequiredStudent],{class:"First Year",branch:"CSE"}); 

}

With underscore 1.8, this will be simplified since we have _.findIndexOf methods.

-one
Mar 17 '17 at 14:18
source share



All Articles