简体   繁体   中英

Best way to access key, value pair inside of an array of objects? in javascript

I'll try my best to explaing as throughly as possible but first I'll just paste what I have so far:

      var test = 'select imei, phone_number from userinfo';
      const result = await pgClient.query(test);
      const resultString = result.rows;  
      
      var a = [];

      for(let i = 0; i < resultString.length; i +=1){
        let obj = resultString[i];
        //let data = [obj];

        // res = data.reduce((acc, curr) => {
        //       acc[curr.imei] = curr.phone_number;
        //       return acc;
        //   }, {} );
          
        a.push(obj)
      }   

      console.log(a)

so basically after querying that select statment, I get an obj like this {imei, number} and then push that to an array so it more looks like this


var jsObjects = [
   {imei: '11', number: '+11'}, 
   {imei: '12', number: '+12'}, 
   {imei: '13', number: '+13'}, 
   {imei: '14', number: '+14'}
];

But if you uncomment the code above and replace a.push(obj) with a.push(res) it can also look like this

[
  { '11': '+11' },
  { '12': '+12'},
]

So the MAIN reason for all of this is becasue im trying to create a function so that

    if (a.imei('11')) {
          return a.phonenumber('+11')
       }

Return the phone number associated with the given imei number.

And the actual question is which format is best to access key, value pair? and how would i access the actual value based on the key? Sorry for being all over, I really dont know how else to explain and ask this. Thank you

I think I understand that you'd like a fast lookup of a number value given an "imei" value. The loop as written in the OP doesn't do anything to the result string except move the same values into a new array called a , so either with a or resultString , do this...

 const jsObjects = [ {imei: '11', number: '+11'}, {imei: '12', number: '+12'}, {imei: '13', number: '+13'}, {imei: '14', number: '+14'} ]; const imeiIndex = jsObjects.reduce((acc, obj) => { acc[obj.imei] = obj.number; return acc; }, {}); console.log(imeiIndex)

With that, given an "imei" value later, the associated number can be looked up fast with...

let someImeiValue = '14';
let quicklyLookedupNumber = imeiIndex[someImeiValue];  // <- this will be '+14'

Also, note...

It's often a good idea to keep the whole object being indexed in the way just described, like this:

 const jsObjects = [ {imei: '11', number: '+11', someOtherProp: 1 }, {imei: '12', number: '+12', someOtherProp: 2 }, {imei: '13', number: '+13', someOtherProp: 3 }, {imei: '14', number: '+14', someOtherProp: 4 } ]; const imeiIndex = jsObjects.reduce((acc, obj) => { acc[obj.imei] = obj; // <-- NEW: store the whole object in the index return acc; }, {}); // now indexed data contains as much info as the original array console.log(imeiIndex); let key = '12'; console.log(`the object at key ${key} is ${JSON.stringify(imeiIndex[key])}`);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM