3

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.

1 Answer 1

2

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,
     // ...
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks this was a good answers. I will have to think about this. The thing with your code is that create a new property and sets it thru a loop. What I was wondering was also conceptual in JavaScript what is possible and what isn't. e.g If One can make name changes to properties. Like changing a reference/pointer name, without any computation.
To my knowledge, that's the only way to do it: you cannot remap properties without creating new ones and removing the originals.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.