对于以下情况,source
是第二个参数为response
的函数,并且response
也是在$.getJSON
请求成功后执行的回调函数,并且因此,假设/devices
端点以正确的格式提供了数据,便可以正确执行。
$( "#devices" ).autocomplete({
source: function(request, response) {
$.getJSON("/devices", { id: 123, term: request.term }, response);
}
});
/devices
路由将返回类似[{id:321, name:'the first name'}, ...]
的内容,但是格式不正确。
如何修改此设置,以便将接收到的数据对象密钥从name
更改为value
,从而使source
成为[{id:321, value:'the name'}, ...]
?
答案 0 :(得分:1)
您可以将回调更改为自己的函数,该函数将修改检索到的数据的格式,然后使用修改后的数据调用h[0] = hh;
h[1] = hh+2;
:
response()
上面,$("#devices").autocomplete({
source: function(request, response) {
$.getJSON("/devices", {id: 123, term: request.term}, function(data) {
const new_data = data.map(({name: value, ...r}) => ({value, ...r}));
response(new_data);
});
}
});
正在拉出.map()
属性(使用destructuring assignment)并将其重命名为name
。 value
正在使用spread syntax,并用于从原始对象中提取剩余的键/值。因此...r
是一个对象,其中包含给定元素的r
属性以外的所有内容。然后,该函数返回一个新对象,使用short hand property names将name
设置为键(其内容为实际值),并与该对象的其余部分合并(因此value
为用于将对象...r
的键/值散布/合并到新创建的键/值中-其行为类似于r
)
答案 1 :(得分:0)
我想您可以使用array.forEach();遍历整个响应数组。
response.forEach(e => {
e.value = e.name;
delete e.name;
});