簡體   English   中英

如何使用jquery遍歷帶有嵌套對象的數組?

[英]how to loop through an array with nested objects using jquery?

如果我有這樣的數組:

var msg = [ {name: ["a1", "a2"], value: "this is A"},
            {name: ["b1", "b2"], value: "this is B"},
            ...
          ]

該數組包含用於客戶端表單驗證的全局錯誤消息。 我設法傳遞了錯誤的輸入(例如“ a1”),現在想知道如何從構造錯誤的數組中獲取相應的消息。


遍歷此數組的最佳方法是什么? 例如,如果我將“ a1”作為參數傳遞到函數中,如何提取“ this is A”作為相應的消息?

inArray並沒有真正的幫助,因為我需要相應的消息,而不是a1的位置。 我也不確定這是否是存儲我的錯誤消息的最佳方法……歡迎提出建議!

感謝幫助!

重新排列您的數據結構:

var my_param = 'b1';

// This is an object, so we can have key/value pairs
var error_codes =
{
    'a1': 0,
    'a2': 0,
    'b1': 1,
    'b2': 1
};

// This is an array because we only need values
var error_messages =
[
    'This is A',
    'This is b'
];

alert(error_messages[error_codes[my_param]]);

這使得設置新的錯誤代碼和消息確實非常容易,並且非常容易理解。 唯一的問題是error_codes[my_param] -它是一個對象,但我們無法執行error_codes.my_param因為它會查找名為“ my_param”的元素,因此使用數組符號可以查找對象鍵。

唯一的其他潛在陷阱是確保您沒有任何結尾的逗號:

var error_codes = { 'a1': 1, }; // NO!

也稱為死亡結尾逗號

這就是我會做的

var myMsg = findMsg('a1')


function findMsg(msgType){
  msg.forEach(function(obj){
    if(inArray(msgType, obj.name) !== -1){
      return obj.value
    }
  })
}

function inArray(key, obj){
 return obj.join().indexOf(key)
}

$.each是對數組的每個元素或對象的每個可枚舉屬性執行操作的jQuery方法。

var value;
$.each(msg, function (i, el) {
  if (el.name.indexOf(name) >= 0) {
    value = el.value;
    return false;  // Stops iteration.
  }
});

如果name"a1"則運行上述命令后, value === "this is A"

簡單又好:

var getMessage = function (name)
{
    var msg = [ ... ];

    for(var i = 0; i < msg.length; ++ i)
        if (msg [i].name.indexOf (name) != -1)
            return msg [i].value;
}

如果找不到名稱,則返回相應的消息或undefined

您可能需要indexOf的填充程序,具體取決於要支持的瀏覽器:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf

暫無
暫無

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

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