This code contains an array of objects that I loop over and append to hidden input fields in the DOM. As these inputs have no ID, I first select them by name using $.each and then check the value by looping over the array using another $.each. If there is a match, I then append some HTML to the DOM.
It works fine, but I have doubts about the code, especially where I am using two $.each. Is there a better way of doing this?
var messages = [
{
"code":"203294641",
"message":"A night costs 332 miles"
},
{
"code":"203294642",
"message":"The night is dark and full of terrors. Costs 32 miles."
},
{
"code":"203294643",
"message":"The night is dark and full of terrors. Costs 67 miles."
},
{
"code":"203294644",
"message":"The night is dark and full of terrors. Costs 423 miles."
},
{
"code":"203294645",
"message":"The night is dark and full of terrors. Costs 431 miles."
},
{
"code":"203294646",
"message":"The night is dark and full of terrors. Costs 76 miles."
}
];
$('input[name="code"]').each(function(){
var inp = $(this);
$.each(messages, function(i) {
if (inp.val() == messages[i].code){
inp.closest('.plan').find('.loyalty').append('<div class="frequent-flyer-message">' + messages[i].message + '</div>');
}
});
});