0

Ive a class like this

class security
{
 public id:number;
 public name:string;
}

Then I have an array of security as follows

let s:security[]=[{id:1,name:'Alex'},{id:2,name:'John'},{id:3,name:'Philip'},{id:4,name:'Mark'},{id:5,name:'Thomas'}];

So a function if I pass the value 0, it will change all names of the array as empty string. If I pass an ID, name should change for that specific ID only.

What I tried was

var id=1;
let s2:security[]=s.find(x=>x.id==id);

Then I have to loop through s2 and change the values. But I guess for both the case rather than looping we can do that change all something like select method in linq

So how can we change object array values for all object or selected without using loop

2 Answers 2

1

The find does not return an array, so s2 is an object. You could just do:

s2.name = '';

However, if you need to change all values (in vanilla js) you have to interate the array.

s.forEach(item => item.name = '');
Sign up to request clarification or add additional context in comments.

2 Comments

OK.. I am using Foreach. But using callback function there.. Not this way as you suggested. Will try this.. Thanks
0

It is not possible to do operations on several elements of an array (array of objects in your case) without having a loop. As a suggestion, you can use javascript's for...of loop if you do not use any library.

for (var security of s) {
  console.log(security);
  // do your operation here
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.