Reputation: 582
I am making a YouTube API request like this:
$.get("https://www.googleapis.com/youtube/v3/channels", {
part: "contentDetails",
id: "somestring",
key: "MY-API-KEY"
} /*, ...*/ )
I have a hidden field with the value id
. The user can choose if they want to use id
or forUsername
.
If I use the jQuery code below I get an error:
unexpected string
and from the API parameter is missing but the value is id
in this case.
$.get("https://www.googleapis.com/youtube/v3/channels", {
part: "contentDetails",
$("#subtype").val(): $("#url").val(),
key: "MY-API-KEY"
}, /*, ...*/ )
How can I use the jQuery code?
Upvotes: 0
Views: 132
Reputation: 272106
You can use the new ES6 object initializer syntax for this:
$.get("https://www.googleapis.com/youtube/v3/channels", {
part: "contentDetails",
[$("#subtype").val()]: $("#url").val(),
key: "MY-API-KEY"
})
Notice the square brackets around computed property name. If you want to support browsers that do not support ES6 then use a simpler approach:
var params = {
part: "contentDetails",
key: "MY-API-KEY"
};
params[$("#subtype").val()] = $("#url").val();
$.get("https://www.googleapis.com/youtube/v3/channels", params);
Upvotes: 1
Reputation: 1
You can use promises ES6 object like this.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
username / id:
<select id="subtype">
<option value="ForUsername">username</option>
<option value="id">id</option>
</select>
<br> Last name: <input type="text" id="url"><br>
<button type="button" id="searchButton">Click Me!</button>
<script>
$("#searchButton").click(function() {
var paramsChooseByUser = $("#subtype").val();
var paramsValue = $("#url").val();
$.get("https://www.googleapis.com/youtube/v3/channels", {
part: "id",
[paramsChooseByUser]: paramsValue,
key: 'someValidKey'
})
.always(function(data) {
console.log(data.responseJSON);
});
});
</script>
</body>
</html>
Upvotes: 0