1

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

4
  • This is invalid syntax SyntaxError: await is only valid in async functions and the top level bodies of modules. It's not so clear what exactly do you want and what are the inputs and expected output. Commented Jul 27, 2021 at 4:31
  • What does your original data actually look like? { '11', '+11' } isn't valid JavaScript or JSON. Commented Jul 27, 2021 at 4:36
  • @Tibrogargan my original data is just a select statment from postgress which looks like this imei number ---------|---------- 11 | +11 etc. This was suppose to look like a table but it didnt format like i thought lol it comes in sort of like this if i rmb correctly { something, \"rows\" : { imei : 11 , phone_number :+11} , something } etc and probably just missing some quotations marks. I don't know if that helps my bad Commented Jul 27, 2021 at 4:42
  • If you know imei is unique ... result.rows.filter( x => curr.imei == x )[0].phone_number Commented Jul 27, 2021 at 4:51

1 Answer 1

2

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])}`);

Sign up to request clarification or add additional context in comments.

4 Comments

AHH i can believe a whole day of "deconstructing" and changing around formats and so many different attempts and you solved in one go :sob: :sob: :sob: THANK YOU SO MUCH!
Happy to help @hamzasheikh. Please note the edit, which points out that to reuse the idea of indexing this way in general, it's a good default habit to keep the whole object being indexed, so any part of it can be found with the O(1) lookup. You'd only not do this if memory usage were a problem.
Keep in mind, JavaScript objects are references so creating multiple index collections doesn't really take up that much memory, since the only thing you store in the collection is a reference to an object. The keys you use to build the index may actually take up more memory than the data it stores.
Thanks @Tibrogargan, agree. My statement was ambiguous, referring to the idea of keeping the index around. In fact, it's actually cheaper to point to the original objects rather than to make smaller copies.

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.