[英]JavaScript loop in jQuery autocomplete, change source array
I am terrible at JavaScript but trying to get better. 我在JavaScript方面很糟糕,但是想变得更好。 I have a simple autocomplete form that uses a JSON call.
我有一个使用JSON调用的简单自动完成表单。 The codes looks like this:
代码如下所示:
$('#TreasureMakers').ajaxChosen({
type: 'GET',
url: '/treasures/find.json',
dataType: 'json',
jsonTermKey: 'q',
placeholder_text_single: 'pick stuff'
}, function (data) {
var results = [];
$.each(data, function (i, val) {
results.push({ value: val.value, text: val.text });
});
return results;
});
And find.json returns results like this: 并且find.json返回如下结果:
[{
value: "17854",
text: "1.00"
},
{
value: "13521",
text: "1.01"
},
...
}]
I would like to try and rewrite the loop to return the same results, but with JSON source data that looks like this: 我想尝试重写循环以返回相同的结果,但使用的JSON源数据如下所示:
results: [{
Treasure: {
accnum: "1.00",
id: "17854"
}
},
{
Treasure: {
accnum: "1.01",
id: "13521"
}
},
...
]}
I imagine this shouldn't be too hard, but I am not even sure where to start. 我想这应该不太难,但是我什至不知道从哪里开始。 I tried doing something like this
我试图做这样的事情
results.push({ value: val.results[0].Treasure.id text: val.results[0].Treasure.accnum });
But the Console returns an error and it does not work. 但是控制台返回错误,并且不起作用。 Can someone help me with this?
有人可以帮我弄这个吗?
You can use Array.prototype.map
for this: 您可以为此使用
Array.prototype.map
:
results.push(val.results.map(function(t){
return { value: t.Treasure.id, text: t.Treasure.accnum };
});
See the MDN documentation for more information about Array.prototype.map
. 有关
Array.prototype.map
更多信息,请参见MDN文档 。
Essentially the map
function does a transformation: transforming the elements of an array from one thing to another. 本质上,
map
函数执行转换:将数组的元素从一件事转换为另一件事。 We're just taking the elements (objects with a property Treasure
), and converting them to objects with properties value
and text
. 我们只是获取元素(具有
Treasure
属性的对象),并将其转换为具有value
和text
属性的对象。 It's very instructive to set a breakpoint in your code and try various map
calls in the console to get a feel for how it works. 在代码中设置一个断点并在控制台中尝试各种
map
调用以了解其工作原理非常有启发性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.