a在json
中有一组数组如下:
[{"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."}]}
我能够从这个数组中识别一个键的值,并使用以下代码识别//do something
:
function getID(name){
$.each(data,function(key,value){ //value = object.value (name)
$.each(value,function(key1,value1){ //value1 = user name (actual names in array)
// name is identified
if(value1 == content){ //content is the "name" user entered
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;
}
});
});
// name is unidentified, new user
var name = content; //content is the "name" user entered
$('#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;
如果名称未在列表中使用以下代码未识别,我正在尝试//do other things
。但是,由于我的数组有6个项目,输出将重复整个过程6次,打印0
我只想要一个输出,一个结果(或者,一个名称及其ID已被识别并打印出什么它与OR有关,名称未被识别,id将被设置为0并打印它的相关内容。)
您可以在 here 链接中找到我的完整代码。如果有人能告诉我我的语法哪部分是错的,那将是非常好的吗?
来自答案的更新代码HERE
答案 0 :(得分:0)
您可以使用Array.filter()
创建一个新数组,该数组仅包含原始数组中传递测试的元素。在这种情况下,您的测试是“此项目的名称是否与用户提供的名称相匹配?”:
success: function(data) {
var data = data || [];
var results = data.filter(function(element, index, array) {
if (element.name === $('#nameText').text(name)) {
return (true);
}
return (false);
});
if (results[0]) {
// an element in the array matched what the user entered
console.log(results[0]);
}
else {
// no name in the array matched $('#nameText').text(name)
// set id to 0 or whatever
}
}
这不是完美的代码;除其他外,它假设$.ajax()
总是返回一个数组,并且该数组不包含重复的名称。但它应该足以让你开始。