Reputation: 14198
I have a url that I create the following way:
let forwardBaseUrl = 'https://www.usergems.com/api/gmail/info?' + $.params({
event: 'Click forwarded link',
email: btoa(userEmail),
properties: {
forwardId: btoa(forwardId)
}
});
Is there an easy way to later add a property to the properties object: I want the same result as this:
let forwardBaseUrl = 'https://www.usergems.com/api/gmail/info?' + $.params({
event: 'Click forwarded link',
email: btoa(userEmail),
properties: {
forwardId: btoa(forwardId),
forwardUrl: 'http://google.at'
}
});
best would be a solution that merges the params. Similar to this (obviously not working):
forwardBaseUrl.params.push({properties: { forwardUrl }})
Upvotes: 2
Views: 685
Reputation: 65808
First, the actual JQuery method is $.param()
, not $.params()
.
Next, if you refactor your code to "build" the "params" object and set up a function that can add a property to your object, then you can regenerate the serialized result anytime you like:
var userEmail = "[email protected]";
var forwardId = "12345";
var props = {
forwardId: btoa(forwardId)
};
var paramObj = {
event: 'Click forwarded link',
email: btoa(userEmail),
properties: props
};
let forwardBaseUrl = 'https://www.usergems.com/api/gmail/info?' + $.param(paramObj);
console.log(forwardBaseUrl);
function changeProperties(prop, value, addRemove){
if(addRemove){
// Add new property to properties object
props[prop] = value;
} else {
// remove property from properties object
delete props[prop];
}
}
// Add a new property to the params "properties" object:
changeProperties("forwardUrl", "http://google.at", true);
// Update serialized params
forwardBaseUrl = 'https://www.usergems.com/api/gmail/info?' + $.param(paramObj);
console.log(forwardBaseUrl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 2
Reputation: 4346
var restObj = {
url: 'https://www.usergems.com/api/gmail/info?'
params: {
event: 'Click forwarded link',
email: 'asda',
properties: {
forwardId: btoa('asd')
}
},
getUrl: function () {
return this.url + $.param(this.params);
}
}
// now you can change params object restObj.params.properties.anotherParam = 'param';
// and get new url console.log(restObjgetUrl.)
Upvotes: 0