Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update JS object value inside an array without looping?

I know that there is a similar question already answered, but mine is different in a way that I just don't want to find it, I just want to update it

I have a JS array of objects like this:

let data = [
  {
    contact_id: 15,
    use_id: 16,
    name: 'ABC',
    phoneNo: '0092123456789',
    checked: false,
  },
  {
    contact_id: 16,
    use_id: 22,
    name: 'DEF',
    phoneNo: '0092123456788',
    checked: false,
  },
  {
    contact_id: 17,
    use_id: 24,
    name: 'XYZ',
    phoneNo: '0092123456787',
    checked: false,
  }
];

Now with this in mind, I have a property named phoneNo which guaranteed unique values.

Now what I want is to toggle the value of checked for a given number.

What I have tried:

for (let i = 0; i < data.length; i++) {
    if (data[i]['phoneNo'] === item.phoneNo) {
        data[i]['checked'] = !data[i]['checked'];
        break; // to make it a little efficent :-)
    }
}

I wrote this code and it worked fine for a while but now I have realized that the list is growing larger and larger and this code iterates over and over again, which is very inefficient.

What I want?

Is there a way that I could directly toggle the value of the property checked given the value of phoneNo without looping over every single item?

like image 584
zsubzwary Avatar asked Dec 05 '22 09:12

zsubzwary


2 Answers

Another option is to change the way your data is stored. If phoneNo is unique you could make data with phone numbers being the keys.

let data2={
  '0092123456789':{
    contact_id: 15,
    use_id: 16,
    name: 'ABC',
    checked: false,
  },
  '0092123456788':{
    contact_id: 16,
    use_id: 22,
    name: 'DEF',
    checked: false,
  },
  '0092123456787':{
    contact_id: 17,
    use_id: 24,
    name: 'XYZ',
    checked: false,
  }};
myPhoneNo = '0092123456787';
data2[myPhoneNo].checked = true;
console.log(data2);
like image 121
depperm Avatar answered Dec 07 '22 23:12

depperm


You can create an object whose keys will be the phone numbers and values will be object that will refer the object in the array data

const obj = {}

let data = [ { contact_id: 15, use_id: 16, name: 'ABC', phoneNo: '0092123456789', checked: false, }, { contact_id: 16, use_id: 22, name: 'DEF', phoneNo: '0092123456788', checked: false, }, { contact_id: 17, use_id: 24, name: 'XYZ', phoneNo: '0092123456787', checked: false, } ];

data.forEach(x => {
  obj[x.phoneNo] = x;
})

let given = '0092123456788';
obj[given].checked = !obj[given].checked

console.log(data)
like image 21
Maheer Ali Avatar answered Dec 07 '22 21:12

Maheer Ali