I possess an array of objects in JSON format as shown below:
[{"id":"0","NameInData":"","name":"","type":"mf","greeting":"Bonjour","message":"GENERIC: Lorem ipsum."},
{"id":"1","NameInData":"alexis","name":"Alexis","type":"mf","greeting":"Bonjour Alexis","message":"ONE: Lorem ipsum."},
{"id":"2","NameInData":"laurence","name":"Laurence","type":"ff","greeting":"Hello Laurence","message":"TWO: Lorem ipsum."},
{"id":"3","NameInData":"francois","name":"Francois","type":"mm","greeting":"Konnichiwa Francois","message":"THREE: Lorem ipsum."},
{"id":"4","NameInData":"dirk","name":"Dirk","type":"mf","greeting":"Ni hao Dirk","message":"FOUR: Lorem ipsum."},
{"id":"5","NameInData":"coline","name":"Coline","type":"ff","greeting":"high 5! Coline","message":"FIVE: Lorem ipsum."}]}
I can extract the value of a particular key from this array and perform some action with it using the code snippet given below:
function getID(name){
$.each(data,function(key,value){
$.each(value,function(key1,value1){
if(value1 == content){
console.log(value.id);
var name = value.name;
$('#nameText').text(name);
console.log("Name: " + name);
var greeting = value.greeting;
$('#greetingText').text(greeting);
console.log("Greeting: " + greeting);
return;
}
});
});
var name = content;
$('#nameText').text(name);
console.log("Name: " + name);
var greeting = data[0].greeting;
$('#greetingText').text(greeting);
console.log("Greeting: " + greeting);
console.log('0');
return;
}
getID(data);
return false;
In case the name is not found within the list, I am attempting to perform other actions. However, due to the array containing 6 items, the process repeats 6 times and prints out '0' multiple times. Ideally, I would like to have only one output, where either a name and its id are identified and corresponding information is printed, or the id is set to 0 for unrecognized names.
You can access my complete code at this link. I would appreciate any insights on identifying any syntax errors in my code.
UPDATED CODE BASED ON ANSWER HERE