Benyi Benyi - 2 months ago 8
AngularJS Question

AngularJS Update Array Items by a Given Key

I'm using AngularJS to create a site.

There's my array:



$scope.replyList = [
{
"id": "85485",
"reply_content": "aaaaaaa",
"reply_gender": "1",
"reply_author": "John"
},
{
"id": "85487",
"reply_content": "bbbbbbb",
"reply_gender": "1",
"reply_author": "Ben"
},
{
"id": "85504",
"reply_content": "ccccccc",
"reply_gender": "1",
"reply_author": "Wang"
}
]


What I want to do is update the item value by a given key
id
.

For example, I'd like to update the content with id
85485
. How can you deal with that?



$scope.replyList[{id: 85475}].reply_content = 'dddddd'; /* failed */


Thank you very much.

Answer

Use Array#find method to get the array element.

$scope.replyList.find(function(v) {
  return v.id == 85475;
}).reply_content = 'dddddd';

// or with ES6 arrow function 

$scope.replyList.find(v => v.id == 85475).reply_content = 'dddddd';


var replyList = [{
  "id": "85475",
  "reply_content": "aaaaaaa",
  "reply_gender": "1",
  "reply_author": "John"
}, {
  "id": "85487",
  "reply_content": "bbbbbbb",
  "reply_gender": "1",
  "reply_author": "Ben"
}, {
  "id": "85504",
  "reply_content": "ccccccc",
  "reply_gender": "1",
  "reply_author": "Wang"
}];

replyList.find(function(v) {
  return v.id == 85475;
}).reply_content = 'dddddd';

console.log(replyList);


For older browser check polyfill option of find method.


UPDATE : If you want to update all the element with that particular id then use Array#forEach method to iterate. Actually, there is no need of Array#find method since you just want to update the value.

$scope.replyList.forEach(function(v) {
   if(v.id == 85475) v.reply_content = 'dddddd';
});

var replyList = [{
  "id": "85475",
  "reply_content": "aaaaaaa",
  "reply_gender": "1",
  "reply_author": "John"
}, {
  "id": "85487",
  "reply_content": "bbbbbbb",
  "reply_gender": "1",
  "reply_author": "Ben"
}, {
  "id": "85504",
  "reply_content": "ccccccc",
  "reply_gender": "1",
  "reply_author": "Wang"
}];

replyList.forEach(function(v) {
  if (v.id == 85475) v.reply_content = 'dddddd';
});

console.log(replyList);