Select item from javascript array - javascript

I need some help getting some details of this array and save it into a variable. I'd like to be able to have the latitude and longitude saved as individual variables. I'm really terrible at selecting pieces of an array.
autofillCollection.addEventListener('retrieve', (event) => {
const featureCollection = event.detail;
const inputEl = event.target;
console.log(featureCollection);
and getting this as a Response, but I'd like to store the latitude and logintude coordinates as variables. I'm terrible at mapping arrays. Can anyone help me select the coordinates indivudally?
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"accuracy": "rooftop",
"match_code": {
"exact_match": false,
"house_number": "UNMATCHED",
"street": "UNMATCHED",
"postcode": "UNMATCHED",
"place": "UNMATCHED",
"region": "UNMATCHED",
"locality": "NOT_APPLICABLE",
"country": "INFERRED",
"confidence": "low"
},
"place_type": [
"address"
],
"place_name": "3329 Old Georgetowne Road, Edmond, Oklahoma 73013, United States",
"address_number": "3329",
"street": "Old Georgetowne Road",
"context": [
{
"id": "postcode.250457836",
"text_en": "73013",
"text": "73013"
},
{
"id": "place.97216748",
"wikidata": "Q862645",
"text_en": "Edmond",
"language_en": "en",
"text": "Edmond",
"language": "en"
},
{
"id": "district.17426156",
"wikidata": "Q485038",
"text_en": "Oklahoma County",
"language_en": "en",
"text": "Oklahoma County",
"language": "en"
},
{
"id": "region.304364",
"short_code": "US-OK",
"wikidata": "Q1649",
"text_en": "Oklahoma",
"language_en": "en",
"text": "Oklahoma",
"language": "en"
},
{
"id": "country.8940",
"short_code": "us",
"wikidata": "Q30",
"text_en": "United States",
"language_en": "en",
"text": "United States",
"language": "en"
}
],
"id": "address.3132590889692730",
"external_ids": {
"carmen": "address.3132590889692730",
"federated": "carmen.address.3132590889692730"
},
"feature_name": "3329 Old Georgetowne Road",
"matching_name": "3329 Old Georgetowne Road",
"description": "Edmond, Oklahoma 73013, United States",
"metadata": {
"iso_3166_2": "US-OK",
"iso_3166_1": "us"
},
"language": "en",
"maki": "marker",
"postcode": "73013",
"place": "Edmond",
"district": "Oklahoma County",
"region": "Oklahoma",
"region_code": "OK",
"country": "United States",
"country_code": "us",
"full_address": "3329 Old Georgetowne Road, Edmond, Oklahoma 73013, United States",
"address_line1": "3329 Old Georgetowne Road",
"address_line2": "",
"address_line3": "",
"address_level1": "OK",
"address_level2": "Edmond",
"address_level3": "",
"postcode_plus": "0802",
"is_deliverable": true,
"missing_unit": false
},
"text_en": "Old Georgetowne Road",
"geometry": {
"type": "Point",
"coordinates": [
-97.46885,
35.62264
]
}
}
],
"attribution": "NOTICE: © 2022 Mapbox and its suppliers. All rights reserved. Use of this data is subject to the Mapbox Terms of Service (https://www.mapbox.com/about/maps/). This response and the information it contains may not be retained. POI(s) provided by Foursquare."
}

You can use Array.map on the main object property features on each feature's geometry object's coordinates property, then flatten the arrays into one with the individual coordinates using Array.flat, each array element will be an individual coordinate, so you can use them as a single variable:
const test = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"accuracy": "rooftop",
"match_code": {
"exact_match": false,
"house_number": "UNMATCHED",
"street": "UNMATCHED",
"postcode": "UNMATCHED",
"place": "UNMATCHED",
"region": "UNMATCHED",
"locality": "NOT_APPLICABLE",
"country": "INFERRED",
"confidence": "low"
},
"place_type": [
"address"
],
"place_name": "3329 Old Georgetowne Road, Edmond, Oklahoma 73013, United States",
"address_number": "3329",
"street": "Old Georgetowne Road",
"context": [
{
"id": "postcode.250457836",
"text_en": "73013",
"text": "73013"
},
{
"id": "place.97216748",
"wikidata": "Q862645",
"text_en": "Edmond",
"language_en": "en",
"text": "Edmond",
"language": "en"
},
{
"id": "district.17426156",
"wikidata": "Q485038",
"text_en": "Oklahoma County",
"language_en": "en",
"text": "Oklahoma County",
"language": "en"
},
{
"id": "region.304364",
"short_code": "US-OK",
"wikidata": "Q1649",
"text_en": "Oklahoma",
"language_en": "en",
"text": "Oklahoma",
"language": "en"
},
{
"id": "country.8940",
"short_code": "us",
"wikidata": "Q30",
"text_en": "United States",
"language_en": "en",
"text": "United States",
"language": "en"
}
],
"id": "address.3132590889692730",
"external_ids": {
"carmen": "address.3132590889692730",
"federated": "carmen.address.3132590889692730"
},
"feature_name": "3329 Old Georgetowne Road",
"matching_name": "3329 Old Georgetowne Road",
"description": "Edmond, Oklahoma 73013, United States",
"metadata": {
"iso_3166_2": "US-OK",
"iso_3166_1": "us"
},
"language": "en",
"maki": "marker",
"postcode": "73013",
"place": "Edmond",
"district": "Oklahoma County",
"region": "Oklahoma",
"region_code": "OK",
"country": "United States",
"country_code": "us",
"full_address": "3329 Old Georgetowne Road, Edmond, Oklahoma 73013, United States",
"address_line1": "3329 Old Georgetowne Road",
"address_line2": "",
"address_line3": "",
"address_level1": "OK",
"address_level2": "Edmond",
"address_level3": "",
"postcode_plus": "0802",
"is_deliverable": true,
"missing_unit": false
},
"text_en": "Old Georgetowne Road",
"geometry": {
"type": "Point",
"coordinates": [
-97.46885,
35.62264
]
}
}
],
"attribution": "NOTICE: © 2022 Mapbox and its suppliers. All rights reserved. Use of this data is subject to the Mapbox Terms of Service (https://www.mapbox.com/about/maps/). This response and the information it contains may not be retained. POI(s) provided by Foursquare."
};
const coordinates = test.features.map((a) => a.geometry.coordinates);
console.log(coordinates.flat());
console.log(...coordinates.flat());

Related

accessing info from an API and displaying in h1

I have an API array I am practicing with. Below is one object from the array called users. I know in order to access the properties such as the firstName I simply write <h1> {users.firstName} </h1>. However, I am trying to display the address property within the "address" object. I thought it would be <h1> {users.address.address} </h1> but that isn't correct.
{
"id": 1,
"firstName": "Terry",
"lastName": "Medhurst",
"maidenName": "Smitham",
"age": 50,
"gender": "male",
"email": "atuny0#sohu.com",
"phone": "+63 791 675 8914",
"username": "atuny0",
"password": "9uQFF1Lh",
"birthDate": "2000-12-25",
"image": "https://robohash.org/hicveldicta.png",
"bloodGroup": "A−",
"height": 189,
"weight": 75.4,
"eyeColor": "Green",
"hair": {
"color": "Black",
"type": "Strands"
},
"domain": "slashdot.org",
"ip": "117.29.86.254",
"address": {
"address": "1745 T Street Southeast",
"city": "Washington",
"coordinates": {
"lat": 38.867033,
"lng": -76.979235
},
"postalCode": "20020",
"state": "DC"
},
"macAddress": "13:69:BA:56:A3:74",
"university": "Capitol University",
"bank": {
"cardExpire": "06/22",
"cardNumber": "50380955204220685",
"cardType": "maestro",
"currency": "Peso",
"iban": "NO17 0695 2754 967"
},
"company": {
"address": {
"address": "629 Debbie Drive",
"city": "Nashville",
"coordinates": {
"lat": 36.208114,
"lng": -86.58621199999999
},
"postalCode": "37076",
"state": "TN"
},
"department": "Marketing",
"name": "Blanda-O'Keefe",
"title": "Help Desk Operator"
},
"ein": "20-9487066",
"ssn": "661-64-2976",
"userAgent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/12.0.702.0 Safari/534.24"
}
You are most likely not looping over the array. To get the user's address, you need to get every object in the users array, then you can run .address.address on each of those objects. See the snippet below:
const users = [{
"id": 1,
"firstName": "Terry",
"lastName": "Medhurst",
"maidenName": "Smitham",
"age": 50,
"gender": "male",
"email": "atuny0#sohu.com",
"phone": "+63 791 675 8914",
"username": "atuny0",
"password": "9uQFF1Lh",
"birthDate": "2000-12-25",
"image": "https://robohash.org/hicveldicta.png",
"bloodGroup": "A−",
"height": 189,
"weight": 75.4,
"eyeColor": "Green",
"hair": {
"color": "Black",
"type": "Strands"
},
"domain": "slashdot.org",
"ip": "117.29.86.254",
"address": {
"address": "1745 T Street Southeast",
"city": "Washington",
"coordinates": {
"lat": 38.867033,
"lng": -76.979235
},
"postalCode": "20020",
"state": "DC"
},
"macAddress": "13:69:BA:56:A3:74",
"university": "Capitol University",
"bank": {
"cardExpire": "06/22",
"cardNumber": "50380955204220685",
"cardType": "maestro",
"currency": "Peso",
"iban": "NO17 0695 2754 967"
},
"company": {
"address": {
"address": "629 Debbie Drive",
"city": "Nashville",
"coordinates": {
"lat": 36.208114,
"lng": -86.58621199999999
},
"postalCode": "37076",
"state": "TN"
},
"department": "Marketing",
"name": "Blanda-O'Keefe",
"title": "Help Desk Operator"
},
"ein": "20-9487066",
"ssn": "661-64-2976",
"userAgent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/12.0.702.0 Safari/534.24"
}];
function App() {
return users.map(el => <h1>{el.address.address}</h1>);
}
// Render it
ReactDOM.render(<App /> , document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
It appears that you are attempting to access the usersobject.
Verify that it is an array by using the following code: const isUserArray = Array.isArray(users);
If the result is true, use a loop, such as users.map(user => <h1>{user.address.address}</h1>), to iterate through the array and access the address property of each user"

Comparing 2 arrays of nested objects while ignoring some properties in Javascript

I'm looking to check an API response for against a set of values but the API response contains some additional info that I'm not interested in checking against
Data to check:
[
{
"address": {
"city": "London",
"firstLine": "23 High Road",
"postCode": "WC1 1AA",
"region": "South East",
"uniqueIdentifier": 239
},
"detail": {
"leaseholdFreehold": "Freehold",
"location": "Satisfactory",
"sector": "Office"
},
"valuation": {
"value": "770000",
"valuationDate": "2018-03-07",
"yield": "7.75"
}
},
{
"address": {
"city": "Leeds",
"firstLinePropertyName": "45 Headrow",
"postCode": "LS2 8AA",
"region": "North East",
"uniqueIdentifier": 287
},
"detail": {
"leaseholdFreehold": "Freehold",
"location": "Good",
"sector": "Residential"
},
"valuation": {
"value": "88000",
"valuationDate": "2018-03-07",
"yield": "8.87"
}
}
]
API response:
[
{
"address": {
"city": "London",
"firstLine": "23 High Road",
"postCode": "WC1 1AA",
"region": "South East",
"uniqueIdentifier": 239
},
"detail": {
"designAndCondition": "",
"developmentCompletionDate": "0001-01-01",
"leaseholdFreehold": "Freehold",
"location": "Satisfactory",
"sector": "Office"
},
"valuation": {
"value": "770000",
"valuationDate": "2018-03-07",
"yield": "7.75"
},
"dbIdentifier": 240
},
{
"address": {
"city": "Leeds",
"firstLinePropertyName": "11 Main Road",
"postCode": "LS2 8AA",
"region": "North East",
"uniqueIdentifier": 282
},
"detail": {
"designAndCondition": "",
"developmentCompletionDate": "0001-01-01",
"leaseholdFreehold": "Freehold",
"location": "Good",
"sector": "Residential"
},
"valuation": {
"value": "88000",
"valuationDate": "2018-03-07",
"yield": "8.75"
},
"dbIdentifier": 239
}
]
So I'm not interested in what values are returned for dbIdentifier, designAndCondition and developmentCompletionDate as they are not in my data to check against but I would like to compare the values for the rest of the properties. In practice these arrays will have more than 2 items
I was initially thinking I would remove the unwanted properties from the objects using the function below
const newArray = responseBody.map(({ dbIdentifierIdentifier, detail: { designAndCondition, developmentCompletionDate }, ...rest }) => rest)
Then ordering by address.uniqueIdentifier, converting to JSON strings and comparing the strings but the function above doesn't work with the nested properties as newArray doesn't contain the detail object at all
newArray:
[
{
"address": {
"city": "London",
"firstLine": "23 High Road",
"postCode": "WC1 1AA",
"region": "South East",
"uniqueIdentifier": 239
},
"valuation": {
"value": "770000",
"valuationDate": "2018-03-07",
"yield": "7.75"
},
"dbIdentifier": 240
},
{
"address": {
"city": "Leeds",
"firstLinePropertyName": "11 Main Road",
"postCode": "LS2 8AA",
"region": "North East",
"uniqueIdentifier": 282
},
"valuation": {
"value": "88000",
"valuationDate": "2018-03-07",
"yield": "8.75"
},
"dbIdentifier": 239
}
]
IS it possible to do it the above way by passing a destructured nested object a map function?
One way to remove the unwanted properties from the API response would be to first copy the response into a new array (to preserve the original response), then delete the properties:
const apiResponse = [{
"address": {
"city": "London",
"firstLine": "23 High Road",
"postCode": "WC1 1AA",
"region": "South East",
"uniqueIdentifier": 239
},
"detail": {
"designAndCondition": "",
"developmentCompletionDate": "0001-01-01",
"leaseholdFreehold": "Freehold",
"location": "Satisfactory",
"sector": "Office"
},
"valuation": {
"value": "770000",
"valuationDate": "2018-03-07",
"yield": "7.75"
},
"dbIdentifier": 240
},
{
"address": {
"city": "Leeds",
"firstLinePropertyName": "11 Main Road",
"postCode": "LS2 8AA",
"region": "North East",
"uniqueIdentifier": 282
},
"detail": {
"designAndCondition": "",
"developmentCompletionDate": "0001-01-01",
"leaseholdFreehold": "Freehold",
"location": "Good",
"sector": "Residential"
},
"valuation": {
"value": "88000",
"valuationDate": "2018-03-07",
"yield": "8.75"
},
"dbIdentifier": 239
}
]
let apiResponseCopy = JSON.parse(JSON.stringify(apiResponse))
var newArray = apiResponseCopy.map(i => {
delete i.dbIdentifier
delete i.detail.designAndCondition
delete i.detail.developmentCompletionDate
return i
})
console.log(newArray)
Then, you should be able to compare the newArray against your data.

how can i filter my services list if i uncheck one of the checkbox from top?

i am working on a small project and i am new with javascript and json. Can anybody help me to sort out the final step. i am very near to complete it, but i am facing some issue in it. i want to filter the results for example when i check Petromin, Showroom Sales and Service Center they will show their results and when i uncheck ( for example petromin ) it removes his value from those service list where his services available but if any other checkbox is still checked and its value also inside those list where pertromin value is already there then it should not remove.
here is my html code
<div id="checkbox_div">
<label><input type="checkbox" value="Petromin">Petromin</label><br>
<label><input type="checkbox" value="Used Cars">Used Cars</label><br>
<label><input type="checkbox" value="Showroom Sales">Showroom Sales</label><br>
<label><input type="checkbox" value="Service Center">Service Center</label><br>
<label><input type="checkbox" value="Quick Service">Quick Service</label><br>
<label><input type="checkbox" value="Spare Parts">Spare Parts</label>
</div>
<ol class="container"></ol>
and here is my javascript code
<script type="text/javascript">
var data;
$('#checkbox_div input').click(function(){
if ($(this).is(":checked")) {
var serv_val = $(this).val().toLowerCase();
$.getJSON( "petromin-en.json", function(jdata) {
data = Object.entries(jdata);
const filteredValues = data.filter(el => {
return el[1].services_list.map(elem => elem.toLowerCase()).indexOf(serv_val) !== -1;
});
//console.log(data);
filteredValues.forEach(function(obj) {
var showroom_val = obj[1].name;
var text_same = showroom_val;
$('.showroom_name').filter(function () {
return $(this).text() === text_same;
}).parent().remove();
$('ol.container').append(
"<div class='inner'><h3 class='showroom_name'>"
+ showroom_val +
"</h3><li class='serv_list'>"
+ obj[1].services_list.join(', ') +
"</li></div>"
);
});
});
}
else if ($(this).not(":checked")){
var uncheck_val = $(this).val();
//
}
});
</script>
and here is my json code
`{ "PETR734": {
"dealerId": "PETR734",
"name": "Riyadh Exit -14",
"latitude": "24.698386",
"longitude": "46.773247",
"state": "Central",
"city": "RIYADH",
"language": "en",
"phoneidentifiers": "frontdesk",
"phones": "920023345",
"email": "info#petromin.com",
"contactWebsite": "https://www.nissan-petromin.com/",
"services": "PA;SRVC;QS;PRTS",
"dealerType": "AC",
"canAcceptLeads": "y",
"spokenLanguages": "ar;en",
"dealerDescription": "Service Center",
"services_list": [
"Petromin",
"Service Center",
"Quick Service",
"Spare Parts"
]
},
"PETR759": {
"dealerId": "PETR759",
"name": "Riyadh Exit 13",
"latitude": "24.700901",
"longitude": "46.770143",
"state": "Central",
"city": "RIYADH",
"language": "en",
"phoneidentifiers": "frontdesk",
"phones": "920023345",
"email": "info#petromin.com",
"contactWebsite": "https://www.nissan-petromin.com/",
"services": "PA;SRVC;QS;PRTS",
"dealerType": "AC",
"canAcceptLeads": "y",
"spokenLanguages": "ar;en",
"dealerDescription": "Service Center",
"services_list": [
"Petromin",
"Service Center",
"Quick Service",
"Spare Parts"
]
},
"PETR764": {
"dealerId": "PETR764",
"name": "Hofouf (TS)",
"latitude": "25.406250",
"longitude": "49.465344",
"state": "Eastern",
"city": "Hofuf",
"language": "en",
"phoneidentifiers": "frontdesk",
"phones": "920023345",
"email": "info#petromin.com",
"contactWebsite": "https://www.nissan-petromin.com/",
"services": "PA;SRVC;QS;PRTS",
"dealerType": "AC",
"canAcceptLeads": "y",
"services_list": [
"Petromin",
"Service Center",
"Quick Service",
"Spare Parts"
]
},
"PETR763": {
"dealerId": "PETR763",
"name": "Khobar (TS)",
"latitude": "26.256590",
"longitude": "50.201419",
"state": "Eastern",
"city": "KHOBAR",
"language": "en",
"phoneidentifiers": "frontdesk",
"phones": "920023345",
"email": "info#petromin.com",
"contactWebsite": "https://www.nissan-petromin.com/",
"services": "PA;SRVC;QS;PRTS",
"dealerType": "AC",
"canAcceptLeads": "y",
"spokenLanguages": "ar;en",
"dealerDescription": "Service Center",
"services_list": [
"Petromin",
"Service Center",
"Quick Service",
"Spare Parts"
]
},
"PETR765": {
"dealerId": "PETR765",
"name": "Qassim (TS)",
"latitude": "26.294617",
"longitude": "43.991607",
"state": "Central",
"city": "Qassim",
"language": "en",
"phoneidentifiers": "frontdesk",
"phones": "920023345",
"email": "info#petromin.com",
"contactWebsite": "https://www.nissan-petromin.com/",
"services": "PA;SRVC;QS;PRTS",
"dealerType": "AC",
"canAcceptLeads": "y",
"services_list": [
"Petromin",
"Service Center",
"Quick Service",
"Spare Parts"
]
},
"PETR753": {
"dealerId": "PETR753",
"name": "Khobar Rashid Mall",
"latitude": "26.299159",
"longitude": "50.181901",
"state": "Eastern",
"city": "KHOBAR",
"language": "en",
"phoneidentifiers": "frontdesk",
"phones": "920023345",
"email": "info#petromin.com",
"contactWebsite": "https://www.nissan-petromin.com/",
"services": "PA;SRVC;QS;PRTS",
"dealerType": "AC",
"canAcceptLeads": "y",
"spokenLanguages": "ar;en",
"dealerDescription": "Service Center",
"services_list": [
"Petromin",
"Service Center",
"Quick Service",
"Spare Parts"
]
},
"PETR752": {
"dealerId": "PETR752",
"name": "Dammam Rayan",
"latitude": "26.411388",
"longitude": "50.092705",
"state": "Eastern",
"city": "DAMMAM",
"language": "en",
"phoneidentifiers": "frontdesk",
"phones": "920023345",
"email": "info#petromin.com",
"contactWebsite": "https://www.nissan-petromin.com/",
"services": "PA;SRVC;QS;PRTS",
"dealerType": "AC",
"canAcceptLeads": "y",
"spokenLanguages": "ar;en",
"dealerDescription": "Service Center",
"services_list": [
"Petromin",
"Service Center",
"Quick Service",
"Spare Parts"
]
},
"PETR762": {
"dealerId": "PETR762",
"name": "Dammam (TS)",
"latitude": "26.441723",
"longitude": "50.048123",
"state": "Eastern",
"city": "DAMMAM",
"language": "en",
"phoneidentifiers": "frontdesk",
"phones": "920023345",
"email": "info#petromin.com",
"contactWebsite": "https://www.nissan-petromin.com/",
"services": "PA;SRVC;QS;PRTS",
"dealerType": "AC",
"canAcceptLeads": "y",
"services_list": [
"Petromin",
"Service Center",
"Quick Service",
"Spare Parts"
]
},
"PETR767": {
"dealerId": "PETR767",
"name": "Tabuk (TS)",
"latitude": "28.438009",
"longitude": "36.466928",
"state": "Western",
"city": "Tabuk",
"language": "en",
"phoneidentifiers": "frontdesk",
"phones": "920023345",
"email": "info#petromin.com",
"contactWebsite": "https://www.nissan-petromin.com/",
"services": "PA;SRVC;QS;PRTS",
"dealerType": "AC",
"canAcceptLeads": "y",
"services_list": [
"Petromin",
"Service Center",
"Quick Service",
"Spare Parts"
]
},
"PETR758": {
"dealerId": "PETR758",
"name": "Riyadh Thumama",
"latitude": "28.830702",
"longitude": "46.730938",
"state": "Central",
"city": "RIYADH",
"language": "en",
"phoneidentifiers": "frontdesk",
"phones": "920023345",
"email": "info#petromin.com",
"contactWebsite": "https://www.nissan-petromin.com/",
"services": "PA;SRVC;QS;PRTS",
"dealerType": "AC",
"canAcceptLeads": "y",
"spokenLanguages": "ar;en",
"dealerDescription": "Service Center",
"services_list": [
"Petromin",
"Service Center",
"Quick Service",
"Spare Parts"
]
}}`
function displayData(filteredData){
// wipe out the current dataset (to replace it with the new one). If filteredData.length === 0, then this will just clear the results.
$('ol.container').html('');
// put the newly found data into the container
filteredData.forEach(location => {
$('ol.container').append(
`<div class='inner'>
<h3 class='showroom_name'>${location.name}</h3>
<li class='serv_list'>${location.services_list.join(', ')}</li>
</div>`
)
})
}
function processData(){
// get all checked checkboxes
const checked = $('#checkbox_div input:checked');
// iterate only the checked checkboxes
checked.forEach(checkbox => {
const currentService = checkbox.val().toLowerCase();
const filteredData = jsondata.filter(location => location.services_list.includes(currentService));
displayData(filteredData);
})
}
$(function(){
$('#checkbox_div input').click(function () {
// All checkboxes do the same thing assuming that the data source is already available.
// If not, then fetch the data first. This assumes that we have data in a global named jsondata.
processData()
});
})
I made some assumptions about your data here for naming purposes. This code is not tested, but I think that it conveys the idea.

How to sort an object of objects in JavaScript?

I have an object of objects named teams:
{
"1": {
"number": "134C",
"robotName": "chazzen",
"name": "Team Discovery - Charlie",
"organization": "Pembroke Academy",
"city": "Pembroke",
"region": "New Hampshire",
"country": "United States"
},
"2": {
"number": "134G",
"robotName": "Ghammer Time",
"name": "Team discovery -Golf",
"organization": "Pembroke Academy",
"city": "Pembroke",
"region": "New Hampshire",
"country": "United States"
},
"3": {
"number": "134K",
"robotName": "Team Discovery kilo",
"name": "Team Discovery -Kilo",
"organization": "Pembroke Academy",
"city": "Pembroke",
"region": "New Hampshire",
"country": "United States"
},
"4": {
"number": "134E",
"robotName": "Team Discovery -Echo",
"name": "Team Discovery - Echo",
"organization": "Pembroke Academy",
"city": "Pembroke",
"region": "New Hampshire",
"country": "United States"
}
}
How do I sort these "sub-objects" alphabetically and numerically based on values such as "number" or "name" in a function?

accessing Javascript object

may be a simple issue but cannot seem to solve it after some searching as well :) .. The scenario is as follows:
Using PhoneGap, am receiving a json object via Ajax using jquery. the object needs to be displayed on a next screen (first is the Search page and the next is the Search result page).
when the object is received, it is being saved in the sessionStorage variable (e.g. sessionStorage.result = data).
but when it is tried to be accessed on the next page, it gives an error saying that the property is unknown. e.g.
var result = sessionStorage.result;
alert(result.response.businesses[0].name);
have also tried:
alert($(result.response.businesses[0].name));
it says that the property is unknow. the basic structure of the json is as follows:
{
"action": "SearchBusiness",
"meta": {
"code": 200,
"message": "OK"
},
"response": {
"searchQuery": {
"categoryId": 4,
"communityId": 4,
"latitude": "",
"longitude": "",
"category": "Grocery Stores",
"community": "Indian/Pakistani",
"searchRadius": "",
"city": "",
"postalCode": ""
},
"businesses": [
{
"businessId": "2",
"name": "Name",
"address": "123",
"phone": "(123) 456 7890",
"city": "any city",
"country": "United States",
"state": "Abc",
"postalCode": "a123",
"url": "",
"logoUrl": null,
"latitude": "0.1951704",
"longitude": "-1.89512",
"categoryId": "4",
"communityId": "4",
"ratings": "0",
"ratingAvg": "0.00",
"distance": 0
}
]
Any help appreciated.
You are wrongly accessing that value,
Try,
var result = JSON.parse(sessionStorage.result);
alert($(result.businesses[0].name));
in your json codes missing } your codes must be like that
{
"action": "SearchBusiness",
"meta": {
"code": 200,
"message": "OK"
},
"response": {
"searchQuery": {
"categoryId": 4,
"communityId": 4,
"latitude": "",
"longitude": "",
"category": "Grocery Stores",
"community": "Indian/Pakistani",
"searchRadius": "",
"city": "",
"postalCode": ""
},
"businesses": [{
"businessId": "2",
"name": "Name",
"address": "123",
"phone": "(123) 456 7890",
"city": "any city",
"country": "United States",
"state": "Abc",
"postalCode": "a123",
"url": "",
"logoUrl": null,
"latitude": "0.1951704",
"longitude": "-1.89512",
"categoryId": "4",
"communityId": "4",
"ratings": "0",
"ratingAvg": "0.00",
"distance": 0
}]
}
}
alert(result.response.businesses[0].name); // it will work i think. no error
also look sessionstroge is there any data
Your Json string is not a valid JSON format plz check the format
{
"action": "SearchBusiness",
"meta": {
"code": 200,
"message": "OK"
},
"response": {
"searchQuery": {
"categoryId": 4,
"communityId": 4,
"latitude": "",
"longitude": "",
"category": "Grocery Stores",
"community": "Indian/Pakistani",
"searchRadius": "",
"city": "",
"postalCode": ""
},
"businesses": [{
"businessId": "2",
"name": "Name",
"address": "123",
"phone": "(123) 456 7890",
"city": "any city",
"country": "United States",
"state": "Abc",
"postalCode": "a123",
"url": "",
"logoUrl": null,
"latitude": "0.1951704",
"longitude": "-1.89512",
"categoryId": "4",
"communityId": "4",
"ratings": "0",
"ratingAvg": "0.00",
"distance": 0
}]
}
}

Categories

Resources