I'm trying to populate a from with the data from the last record in my db with $.getJSON.
The GET returns the JSON but I can't get the data to populate the fields. I'm a complete neewb to much of this.
$.getJSON("loadloads.php", function (data) {
document.getElementById("LoadNumber").innerHTML = data.LoadNumber
});
this is the JSON returned, copied from firebug.
[{
"value": {
"LoadNumber": "227303",
"OrderDate": "2013-04-09",
"ShipDate": "2013-04-09",
"ShipTime": "12:00:00",
"DeliveryDate": "2013-04-10",
"DeliveryTime": null,
"PurchaseOrderNumber": "0002323803",
"CustomerId": "200540",
"Rate": "801.08",
"EmployeeId1": "1",
"EmployeeId2": "1",
"CarrierId": "201383",
"CarrierRate": "700",
"Tarp": "NO",
"Status": "Dispatched",
"Notes": "Pls check in as an All Points Inc. carrier. V-boards reg. Shipper tracking we need Proof of delivery faxed or called in A.S.A.P (within 24 hours) Need printed name of person signing for load. Must haul 48K min.",
"LoadTypeId": "1",
"LoadType": "Flatbed",
"BillingNotes": "608.48 + 192.60",
"InvoiceDate": null,
"PayDate": null,
"DestinationNext": null,
"Covered": "0",
"CompanyName": "GAF Materials Corp.",
"CarrierName": "Daniel Zamora",
"FN1": "Craig",
"FN2": "Craig"
}
}]
this is the input box
<label for="LoadNumber">Load Number :
<input type="text" size="12" id="LoadNumber" Name="LoadNumber" tabindex="-1" />
</label>
The JSON defines an array which has one entry, which is an object, which has one property, value, which is an object with a bunch of properties, of which LoadNumber is one. Separately, since LoadNumber is an input element, you'd use .value rather than .innerHTML.
So instead of
document.getElementById("LoadNumber").innerHTML = data.LoadNumber
It should be:
document.getElementById("LoadNumber").value = data[0].value.LoadNumber;
(The semicolon isn't absolutely necessary, but I strongly recommend not relying on the Horror of Semicolon Insertion.)
data refers to the array as a whole, so [0] gives us the first entry, then .value gives us the value property of that object, and .LoadNumber gives us the LoadNumber property of that object. More verbosely:
var firstEntry = data[0];
var valueObject = firstEntry.value;
document.getElementById("LoadNumber").value = valueObject.LoadNumber;
Of course, since you're using jQuery, you could use val instead:
$("#LoadNumber").val(data[0].value.LoadNumber);
Related
I want to update a single Object in my localStorage. I made a detail page, where I can submit new values (progress and value)
When I want to update the value, it changes the value in both objects. How can I change just one object.
Here is my deployment link.(its work in progress)
https://mastery-app.herokuapp.com/
This is my localStorage array:
skills[
{
"title": "Sewing",
"imageSrc": "images.unsplash.com",
"description": "Make your own clothes",
"category": "crafting",
"progress": 500,
"isDone": false,
"rank": 0,
"value": 0
},
{
"title": "Crocheting",
"imageSrc": "images.unsplash.com",
"description": "Interlock loops of yarn",
"category": "crafting",
"progress": 500,
"isDone": false,
"rank": 0,
"value": 0
}
]
This is how I update the localStorage:
const update = skills.map((skills) => {
skills.title === skills.title;
const updateProgress = skills.progress - value;
const rankNumber = parseInt(ranking);
const updateRank = skills.rank + rankNumber;
console.log(updateRank);
const updateValue = skills.value + value;
return {
title: skills.title,
rank: updateRank,
description: skills.description,
progress: updateProgress.toFixed(1),
imageSrc: skills.imageSrc,
category: skills.category,
isDone: false,
value: updateValue,
};
});
localStorage.setItem('skills', JSON.stringify(update));
You may consider using the find method to find the object you want to update. map is not the right function to be used for your use case.
Also skills.title === skills.title; has no effect at all (Maybe you wanted to use an if statement to do some kind of filtering by using title but that always would return true). Please remove that.
Now, I don't exactly know which field are you going to use to search for the object you want to update, but it has to be unique. If none of the fields in the objects are unique you should consider adding an unique id field in the skills objects. But if title is unique you can use the title to search. Then you can do something like the pseudo code below:
const toUpdate = skills.find(skill => skill.title === your_title_here)
toUpdate.field_to_update_1 = some_value_1
toUpdate.field_to_update_2 = some_value_2
localStorage.setItem('skills', JSON.stringify(skills))
Please also check the MDN docs to see how map, find and other array methods work and some of their use cases.
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.
I want to get a list of all the values that are now available in the field State, for example, that is, approximately so ['Open', 'Closed', 'Hold']
I try
var arrSprint = issue.fields['State'];
console.log(arrSprint);
But this command outputs to me characteristics this fileds
"foregroundColor": "#444",
"presentation": "Open",
"colorIndex": "0",
"description": "null",
"name": "Open",
Possible values can be retrieved from the respective ProjectCustomField. To get a ProjectCustomField, either call issue.project.findFieldByName('State'), or better add a requirement like
State: {
type: entities.State.fieldType
}
which will allow you to access the ProjectCustomField via ctx.State.
I have a list of data displayed on my page that is broken down into divs. Each div represents an array of data in my object, pretty common.
I am trying to add a text box to my page where I can filter out the data and it will narrow down the results shown on the page as more data is entered into the text box.
For that, I added a filter on my ngFor like so: *ngFor="let x of data | filter: filterString".
My text-box then uses ngModel to filter that data down:
<input type="text" class="form-control" placeholder="Filter..." name="ruleFilter" id="ruleFilter" [(ngModel)]="filterString" (keyup)="onFilter($event)">
The issue I am having is that the filter seems to only be working with the top layer of data in my object. For example, the data below is what one of the results looks like in my ngFor loop. I can search Omaha just fine since its in the top level and it filters it down correctly.
However, If I look for something like Campus which is nested inside Attribute, it doesn't find it in the filter and no results are shown.
{
"RuleParentID": "618",
"RuleVersionID": "18",
"MappedValue": "1",
"ProcessingOrder": 1,
"KeyID": "1",
"Value": "Omaha",
"IsRuleRetired": "0",
"UserImpactCount": "0",
"Attribute": [
{
"AttributeID": "6",
"AttributeName": "Campus",
"Operator": {
"OperatorID": "3",
"OperatorName": "In List",
"SqlOperator": "IN"
},
"AttributeValue": [
{
"AttrValue": "1",
"Value": "Omaha",
"IsValueRetired": "0",
"disabled": "False"
}
]
},
{
"AttributeID": "14",
"AttributeName": "Grade",
"Operator": {
"OperatorID": "1",
"OperatorName": "Greater Than",
"SqlOperator": ">"
},
"AttributeValue": [
{
"AttrValue": "14",
"Value": "14",
"IsValueRetired": "0",
"disabled": "False"
}
]
}
]
}
Is there any way to have the model look at all layers of the object for my binding instead of just the top layer (which I only assume its doing at this time) ?
Update: Here is a plunker of what my basic setup is like: https://plnkr.co/edit/eywuWmPRseUkmVPbTEOf?p=preview
You will see the data model that searches by the top level properties just fine, but when I search for something nested, I don't get any results back.
If I understand well the question, I think that to flat the data will help you:
var flattenObject = function(ob) {
var toReturn = {};
for (var i in ob) {
if (!ob.hasOwnProperty(i)) continue;
if ((typeof ob[i]) == 'object') {
var flatObject = flattenObject(ob[i]);
for (var x in flatObject) {
if (!flatObject.hasOwnProperty(x)) continue;
toReturn[i + '.' + x] = flatObject[x];
}
} else {
toReturn[i] = ob[i];
}
}
return toReturn;
};
let newData = flattenObject(data);
Code source: https://gist.github.com/penguinboy/762197
To achieve expected result , use below option
1.In your component below variable
jsonVal:any=JSON; // for using JSON.stringify and indexOf
Use *ngIf to filter value from input with indexOf
<input type="text" [(ngModel)]="filterString">
<div *ngFor="let data of result">
<div *ngIf="jsonVal.stringify(data).indexOf(filterString)!= -1">{{data| json}}</div>
</div>
code sample for reference - https://stackblitz.com/edit/angular-ht2afv?file=app/app.component.html
Just for testing , I have added another Object with Campus2 and Omaha2
When filtering on a nested property of data you can use the map function or similar.
This will be in your component and not the template. Filtering using pipes in the template is discouraged by the Angular team for performance reasons.
Instead I would do something like this:
const data = [{//your data}]
let filteredData = [];
data.map(val => {
if (val.Attribute.filter(name => name.AttributeName === "Foo").length > 0) {
filteredData.push(val)
}
});
I am assuming your data is an array of objects.
Beware I am mutating my data object. To avoid this you do this:
const data = [{//your original data}]
const dataToFilter = JSON.Parse(JSON.stringify(data))
This will make copy of your data without references to your original object. Useful if you want to clear your filter. Not useful if your data object contains functions.
On re-reading your question I think this is not the solution you were looking for but rather a method to look anywhere in the data. For this you should probably flatten your data as suggested by Zelda7. Another approach would be to extend a filtering method to explicitly filter on all relevant fields.
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.