Faisal Ahmed
Faisal Ahmed

Reputation: 35

some better way to find out and change an object from an array using its attribute

Suppose I have an array(Accounts[]) of objects whose class is defined as:

export const AccountSchema = {
    name: ACCOUNT_SCHEMA,
    primaryKey: 'id',
    properties: {
        id: 'int',    // primary key
        name: { type: 'string', indexed: true },
        type: 'string',
        balance: 'int',
        note:'string',
        creationDate: 'date',
    }
};

Now for example, I know an account name Salary AC and I want to change balance of this account.

For example, I want something like below code in JavaScript (some better or the best way).

In below code using ==means equality & : means assignment

for(var i=0; i<Accounts.length; i++) {
   if (Accounts[i].name == 'Salary AC') {
      Accounts[i].balance: 500;
   }
}  

Thanks in advance

Upvotes: 0

Views: 24

Answers (1)

bugs
bugs

Reputation: 15313

You can use array#find (docs)

Accounts.find(item => item.name === 'Salary AC').balance = 500

Keep in mind that find will always return the first element that satisfies the condition, so it wouldn't be an option if you have multiple accounts with the same name. In that case, use array#filter and loop over the returned array.

Upvotes: 1

Related Questions