Reputation:
Is it possible to change the name of a parameter in a JavaScript object?
My question arises from that the JQuery AutoComplete is very fussy about parameter names and requires a parameter name either label or value.
My data object.
data....
data.receivers[].id
data.receivers[].name
data....
What I would like to do is make an alias/reference or similar conceptual like this.
data.receivers[].label = data.receivers[].name
So I would like to change a parameter from name to label. I have done it this way but I don't like to duplicate the data which I believe .map does.
var callBack = function(data) {
var autoCompleteData = jQuery.map(data.receivers, function(receiver, i){
return {label: receiver.name, id: receiver.id };
});
$("input#reciever").autocomplete({
source: autoCompleteData,
focus: function(event, receiver) {
$("input#reciever").val(receiver.item.label);
return false;
},
select: function(event, receiver) {
$("input#reciever").val(receiver.item.label);
$("input#recieverId").val(receiver.item.id);
return false;
}
});
}
Ps. I could change the JSON return data from my server but I want to keep the names logical and intuitive and not be forced to model by data object according to JQuery's constraints.
Upvotes: 3
Views: 331
Reputation: 262999
If you want to update your object collection in-place, you can use $.each() instead of $.map()
:
$.each(data.receivers, function() {
this.label = this.name;
delete this.name;
});
$("input#reciever").autocomplete({ // suggest $("#receiver") instead
source: data.receivers,
// ...
});
Upvotes: 2