簡體   English   中英

訪問對象數組中的鍵、值對的最佳方法? 在 JavaScript 中

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

我會盡我最大的努力解釋清楚,但首先我會粘貼我目前所擁有的:

      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)

所以基本上在查詢了 select 語句之后,我得到了一個像 {imei, number} 這樣的對象,然后將它推送到一個數組中,這樣它看起來更像這樣


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

但是如果你取消注釋上面的代碼並將 a.push(obj) 替換為 a.push(res) 它也可以是這樣的

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

所以這一切的主要原因是因為我試圖創建一個函數,以便

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

返回與給定 imei 號碼關聯的電話號碼。

實際問題是哪種格式最適合訪問鍵值對? 以及如何根據密鑰訪問實際值? 對不起,我已經結束了,我真的不知道如何解釋和問這個。 謝謝

我想我知道您希望快速查找給定“imei”值的數字值。 除了將相同的值移動到名為a的新數組中之外,OP 中編寫的循環不會對結果字符串執行任何操作,因此使用aresultString執行此操作...

 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)

有了這個,稍后給定一個“imei”值,可以使用...

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

另外請注意...

以剛剛描述的方式對整個對象進行索引通常是一個好主意,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM