I have the following API Data:
[
{
"symbol": "AAPL",
"name": "Apple Inc.",
"price": 144.98,
"changesPercentage": -1.22,
"change": -1.79,
"dayLow": 142.54,
"dayHigh": 146.96,
"yearHigh": 150,
"yearLow": 93.7125,
"marketCap": 2419368132608,
"priceAvg50": 138.45343,
"priceAvg200": 131.05212,
"volume": 113982837,
"avgVolume": 85057328,
"exchange": "NASDAQ",
"open": 144.81,
"previousClose": 146.77,
"eps": 4.449,
"pe": 32.587097,
"earningsAnnouncement": "2021-07-27T16:30:00.000+0000",
"sharesOutstanding": 16687599204,
"timestamp": 1627504655
}
]
And here is my code with a fake API code:
var $stocks = $('#stocks');
$.ajax({
type: 'GET',
url: 'https://financialmodelingprep.com/api/v3/quote/AAPL?apikey=c0dabd2d8a382584d2144bdefde830f2',
success: function (percent) {
$.each(percent, function (i, item) {
$stocks.append(percent.changesPercentage);
})
}
});
All I would like to do is get the changesPercentage and display it on my webpage with HTML and CSS. I will have various data from different companies, so a versatile solution would be very helpful.
You're trying to get changesPercentage from percent, which is the entire response array. So that property would be undefined.
Instead, it looks like you want to get that value from each element in the array. For that you would use the item parameter of the callback function in $.each:
$stocks.append(item.changesPercentage);
Alternatively, you could also use the i parameter as an indexer for the original array:
$stocks.append(percent[i].changesPercentage);
As an aside, this appears to be a result of using poor variable names which confuse yourself. percent is a misleading name for an array of objects. Something like results would be better, or perhaps the plural form of whatever noun actually describes what these API results are.
Names are important in code. They carry information about what that thing is and how it can be used.
Related
My API has two records: Car and Account. An Account may have many associated Car records.
I have REST routes for updating deleting creating a car record.
Normally, a GET route for call for all cars would look like this: /car
A route for a specific car would be /car/:id the :id being from the Car.
How would I set up a REST route to get call cars by account ID? Would I have to do something like account/:id/car?
You can do it hierarchical with URI path or use querystring. The URI RFC covers this I think.
/cars?account=123
/accounts/123/cars
As of REST you can return a hyperlink with the upper, something like
{
"operation": "ListCarsAssociatedWithAccount(accountId)",
"method": "POST",
"URI": "/accounts/{accountId}/cars",
"params": {"accountId": {"type":"AccountId"}}
}
The REST client should know only about how to call the ListCarsAssociatedWithAccount(accountId) and the URI and body templates can be filled with the params.
With this approach you can even describe the body of the POST request and the expected response if you want to and automate it further:
{
"operation": "ListCarsAssociatedWithAccount(accountId, x)",
"params": {
"accountId": {"type": "AccountId"},
"x": {"type": "Number"}
},
"method": "POST",
"URI": "/accounts/{accountId}/cars",
"body": {
"q": {
"w": {"param": "x"}
}
},
"returns": {
"type":"CarList",
}
}
ListCarsAssociatedWithAccount(123, 5)
->
POST "/accounts/123/cars"
{
"q": {
"w": 5
}
}
200 OK
{
operations: [...],
values: [
{"carId": 34, operations: [...]},
{"carId": 3, ...},
{"carId": 4, ...},
...
]
}
->
var cl = new CarList();
cl.support(o.operations);
var item1 = new Car("carId": o.values[0].carId);
item1.support(o.values[0].operations);
cl.add(item1)
...
return cl;
Something similar (but a lot more complex) is used in the Hydra framework. http://www.hydra-cg.com/
The endpoints are consider flexible and cheap to add (and modify while preserving backward compatibility). But normally something like this:
GET/UPDATE/DELETE: accounts/:id/cars/:carid
GET(search)/CREATE: accounts/:id/cars/
and you could also get the same information from:
GET/UPDATE/DELETE: cars/:carid
GET(search)/CREATE: cars/
Note that on the backend, you should be using the same logic for both endpoints though (reusing code here between the endpoints). The idea of the first set of endpoints is that you can drill into specific elements in a logical/hierarchical manner. So if you needed some sub element of cars for a specific account:
GET/UPDATE/DELETE: accounts/:id/cars/:carid/wheels
That allows maximal use/reuse of data without the need to constantly add filters based on account/car in the various endpoints.
NOTE: normally the endpoints would be pluralized so that you can do searches from the same endpoint, so `GET /accounts' could include search parameters to gather result sets.
Could anyone make me understand the below scenario because I tried searching the web and unable to find any info.
I have the below code which does not work because infox is null. But when i change it "infox: []" then it works fine. I need to understand why is it so ?
data:{
infox:null
}
methods: {
loadmore: function () {
axios.get(this.url)
this.infox.push(...response.data);
}}
Next I want to understand what does the three dot stands for in ...response.data and why I cannot code in the below manner without three dots which makes more sense. I would really appreciate if you could point me to the source.
methods: {
loadmore: function () {
axios.get(this.url)
this.infox.push(response.data);
}}
Below is my JSON data
[
{
"Categories": "Fashion",
"Clicked": 30,
"EndDate": "2019-08-21",
"HomepageSpotlight": "No",
"ImageMainPage": "/static/images/fashion16.jpg",
"MainPage": "Yes",
"Mainhomepage": "No",
"Rating": 5,
"SlugTitle": "buy-clothes-with-50-Off",
},
{
"Categories": "Fashion",
"Clicked": 145,
"EndDate": "2019-08-21",
"HomepageSpotlight": "No",
"ImageMainPage": "/static/images/fashion10.jpg",
"MainPage": "Yes",
"Mainhomepage": "No",
"SlugTitle": "get-upto-60-off-on-jeans",
}
]
The this.infox variable refers to the infox:null in your example, so it does not work because null, obviously, does not have the method push.
When you change the infox to an Array like infox: [] then it works because an Array does have the method push.
Three dots operator is a new feature in ES6, you can read about it in a lot of articles, for example here: https://dev.to/sagar/three-dots---in-javascript-26ci
In your case the this.infox.push(...response.data) will populate each element of the data into the infox array. Your data is the array it'self, so it will copy the data array to the infox array.
The this.infox.push(response.data) string will result in putting all the data array in just one element of the infox array.
I'm having an issue with building a private Zapier integration since Zapier can only use arrays as outputs instead of objects. The array I needs to call is nested 2 levels into my API results, and the key it needs to call is a variable unique to the task called (but I can I can make it part of the input data).
So to get the correct array, the javascript would need to be something like "return results.custom_field_values[bundle.inputData.id]", but I can't find a way to get the input data variable to be accepted in the results like.
Is this possible? I couldn't find a solution in the support documentation.
Here is the call I'm making:
const options = {
url: `https://api.mavenlink.com/api/v1/custom_field_values.json?subject_type=story&with_subject_id=${bundle.inputData.subject_id}& custom_field_name=Active Assignee`,
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${bundle.authData.access_token}`,
'Accept': 'application/json'
},
params: {
'subject_id': bundle.inputData.with_subject_id,
'display_value': 'Active Assignee'
}
}
return z.request(options)
.then((response) => {
response.throwForStatus();
const results = z.JSON.parse(response.content);
// You can do any parsing you need for results here before returning them
return results.custom_field_values[bundle.inputData.id];
});
Here is my result when I call just results.custom_field_values:
{
"233451615": {
"can_edit": true,
"subject_type": "story",
"account_id": 4150797,
"subject_id": 385046515,
"updated_at": "2019-03-18T13:54:28-07:00",
"value": [
638945
],
"display_value": "Irma Davila",
"setter_id": "10976265",
"custom_field_id": "181017",
"created_at": "2019-03-05T07:00:15-08:00",
"custom_field_name": "Active Assignee",
"type": "single",
"id": "233451615"
}
}
What I'm trying to do is call only the array within the object that in this case is "233451615" (It's the same as the ID). However, even though the object is different every time, it can be provided as a variable via the input.
Thanks to anyone willing to help!
You need to use [] notation Ref
Change this
"return results.custom_field_values.{bundle.inputData.id}"
to this
"return results.custom_field_values[bundle.inputData.id]"
Have you tried bracket notation instead of dot notation?
something like this :
results.custom_field_values[{bundle.inputData.id}]
Also make sure that bundle.inputData.id is the correct value.
I am new to Underscore. I have a json array which is pasted below. If I want to filter the below array based on developed field having "yes" as value. How can I do using Underscore.js. Currently I am iterating over the content of array and manually selecting the objects and populating in into another array. Is there a better way to do using Underscore?
{
"content": [
{
"stateName": "Karnataka",
"population": 1000000,
"developed": "yes"
},
{
"stateName": "Kerala",
"population": 1000000,
"developed": "yes"
},
{
"stateName": "Tamilnadu",
"population": 1023213213213,
"developd": "yes"
},
{
"stateName": "Bsadasd",
"population": 1023213213213,
"developed": "no"
}
]
}
Not sure if I'm missing something here but the obvious underscore function is filter:
var developedStates = _.filter(data.content, function(state){
return state.developed == 'yes';
});
You can filter an array on its properties by using _.where :
where _.where(list, properties)
Looks through each value in the list, returning an array of all the values that contain all of the
key-value pairs listed in properties.
which leads to
var filtered = _.where(data.content, {developed: "yes"});
and a demo http://jsfiddle.net/nikoshr/NExZC/
As far as I know, underscore doesn't have a way to help you with this task. You can do this without using underscore with a native Javascript method called select:
var filteredArray = originalArray.select(function(item, index) {
return item.developed == "yes"; // Include this item if it has a proper value
});
Note that the select method is only available in browsers that support EcmaScript 5 specifications, so for older browsers you will need some supporting library like es5-shim.
I have a json url that returns data in the format
{
"photos" : [
{
"id": 1, "image":"https://path/to/my/image/1.jpg"
},
{
"id": 2, "image":"https://path/to/my/image/2.jpg"
}
]
}
I'm using the json in a javascript function, and need to manipulate it to remove the root key. i.e. I want something that looks like
[
{
"id": 1, "image":"https://path/to/my/image/1.jpg"
},
{
"id": 2, "image":"https://path/to/my/image/2.jpg"
}
]
I've been hacking around with various approaches, and have referred to several similar posts on SO, but nothing seems to work. The following seems like it should.
var url = 'http://path/to/my/json/feed.json';
var jsonSource = $.getJSON( url );
var jsonParsed = $.parseJSON(jsonSource);
var jsonFeed = jsonParsed.photos
What am I doing wrong?
A couple of issues there.
That's invalid JSON, in two different ways. A) The : after "photos" means that it's a property initializer, but it's inside an array ([...]) when it should be inside an object ({...}). B) There are extra " characters in front of the images keys. So the first thing is to fix that.
You're trying to use the return value of $.getJSON as though it were a string containing the JSON text. But $.getJSON returns a jqXHR object. You need to give it a success callback. That callback will be called with an object graph, the JSON is automatically parsed for you.
Assuming the JSON is fixed to look like this:
{
"photos": [
{
"id": 1,
"image": "https://path/to/my/image/1.jpg"
},
{
"id": 2,
"image": "https://path/to/my/image/2.jpg"
}
]
}
Then:
$.getJSON(url, function(data) {
var photos = data.photos;
// `photos` now refers to the array of photos
});