NickJ
NickJ

Reputation: 9559

Modify array value in Javascript

I have the following Javascript in which I am trying to modify a single field of a property in an array. The array itenms might have any number of fields, but the template will only specify the rowId (to identify the item) and the new property value.

Here's the code:

function findRow(rowId) {
    return this.seniorityList.find(element => element.rowId==rowId);
}

this.seniorityList = [
    {Seniority:0, Rate:1.1, rowId:'row-0'},
    {Seniority:6, Rate:1.3, rowId:'row-1'},
    {Seniority:12, Rate:1.6, rowId:'row-2'},
    {Seniority:18, Rate:1.9, rowId:'row-3'},
    {Seniority:24, Rate:2.1, rowId:'row-4'}
];
let template = {Rate:99.99, rowId:'row-2'}

let row = findRow('row-2');

row = {...row, ...template };

console.log('array '+JSON.stringify(this.seniorityList));

I was rather hoping that the output would show the updated value of Rate but in fact, it shows the original value. If I do a console.log of the individual row then it correctly shows the change, but the array itself is unchanged. How can I update the array?

Upvotes: 0

Views: 238

Answers (2)

disinfor
disinfor

Reputation: 11533

Since you essentially have an Object in your array, you could use the property:

function findRow(rowId) {
  return this.seniorityList.find(element => element.rowId == rowId);
}

this.seniorityList = [{
    Seniority: 0,
    Rate: 1.1,
    rowId: 'row-0'
  },
  {
    Seniority: 6,
    Rate: 1.3,
    rowId: 'row-1'
  },
  {
    Seniority: 12,
    Rate: 1.6,
    rowId: 'row-2'
  },
  {
    Seniority: 18,
    Rate: 1.9,
    rowId: 'row-3'
  },
  {
    Seniority: 24,
    Rate: 2.1,
    rowId: 'row-4'
  }
];
let template = {
  Rate: 99.99,
  rowId: 'row-2'
}

let row = findRow('row-2');

row.Rate = 99.99;

console.log('array' + JSON.stringify(this.seniorityList))

Upvotes: 0

apple apple
apple apple

Reputation: 10591

{...row, ...template } create a new instance, you can use Object.assign to overwrite the content (or assign them manually).

function findRow(rowId) {
    return seniorityList.find(element => element.rowId==rowId);
}

let seniorityList = [
    {Seniority:0, Rate:1.1, rowId:'row-0'},
    {Seniority:6, Rate:1.3, rowId:'row-1'},
    {Seniority:12, Rate:1.6, rowId:'row-2'},
    {Seniority:18, Rate:1.9, rowId:'row-3'},
    {Seniority:24, Rate:2.1, rowId:'row-4'}
];
let template = {Rate:99.99, rowId:'row-2'}

let row = findRow('row-2');

//or row.Rate = template.Rate
Object.assign(row,template)

console.log('array '+JSON.stringify(seniorityList));

Upvotes: 3

Related Questions