trying to locate the word 'London' from a generated JSON array entered from a user.
response 200 (API example):
{
"latitude": 52.24593734741211,
"longitude": -0.891636312007904,
"addresses":
["10 Watkin Terrace, , , , , Northampton, Northamptonshire",
"12 Watkin Terrace, , , , , Northampton, Northamptonshire",
i wrote a function:
request.onload = function() {
var data = JSON.parse(this.response);
if(request.status >= 200 && request.status < 400) {
var city = data.addresses;
var london = 'London';
var check = city.includes(london);
if(check) {
console.log(city);
} else {
console.log('not in london');
var show = document.getElementById('incorrect_postcode').style.visibility='visible';
I'm unsure if I misunderstand the API or if somethings wrong here... the statement is always false.
Also tried for loop to search the length of the array to locate 'London', to no avail
Thanks.
The addresses array is a list of strings, each string being an address. So, none of the strings will exactly equal 'London', because there is more to an address than the city.
You could loop through the array of addresses and check if each string contains 'London', but that would also match any addresses where London is in the street name.
The better way would be to loop through the array of addresses and parse each address string to pull out the city value. Then compare the city value to 'London'.
Note: I am assuming the second-to-last value is the city.
const data = {
"latitude": 52.24593734741211,
"longitude": -0.891636312007904,
"addresses": [
"10 Watkin Terrace, , , , , Northampton, Northamptonshire",
"12 Watkin Terrace, , , , , Northampton, Northamptonshire",
"221B Baker Street, , , , , London, "
]
};
let desiredCity = 'London';
// array index of city after splitting the addresses
const CITY_POSITION = 5;
console.log('Addresses in ' + desiredCity + ':');
for(let i = 0; i < data.addresses.length; i++) {
// split the address on the delimiter, ', '
let addr = data.addresses[i].split(', ');
if(addr[CITY_POSITION] === desiredCity) {
console.log(data.addresses[i]);
}
}
If you simply want true/false check, you can go, like:
var input = {
"latitude": 52.24593734741211,
"longitude": -0.891636312007904,
"addresses":[
"10 Watkin Terrace, Northampton, Northamptonshire",
"12 Watkin Terrace, Northampton, Northamptonshire",
//"Baker Street, London, England",
"Londonderry, Ireland"
]
};
const isLondon = obj => obj.addresses.some(addr => addr.match(/, London,/));
console.log(isLondon(input));
Welcome to SO
If we assume the JSON request is working, then no need to include that part.
The reason your example does not work, is that includes is looking for the complete string
Instead loop over the array and look at each string
NOTE: If you use search or indexOf, you may find London in Londonderry
var response = `{
"latitude": 52.24593734741211,
"longitude": -0.891636312007904,
"addresses":
[
"10 Watkin Terrace, , , , , Northampton, Northamptonshire, NN1 1ED",
"Bishop Street, , , , , Londonderry, BT48 6PQ",
"12 Watkin Terrace, , , , , Northampton, Northamptonshire, NN1 1ED",
"10 Downing Street, , , , , LONDON, SW1A 2AA"
]
}`
var data = JSON.parse(response);
var addrs = data.addresses;
console.log(addrs)
var city = 'London'.toLowerCase();
var check = addrs.filter(function(addr) {
var thisCity = addr.split(",")[5].toLowerCase().trim()
console.log(city,thisCity)
return thisCity === city
})
if (check.length > 0) {
console.log("Yes, in "+city,check);
} else {
console.log('not in london');
}
Here is a simple search
var data ={
"latitude": 52.24593734741211,
"longitude": -0.891636312007904,
"addresses":
["10 Watkin Terrace, , , , , Northampton, Northamptonshire",
"12 Watkin Terrace, , , , , Northampton, Northamptonshire",
"london",
"londonderry, Ireland",
"London Road"
]}
var searchFor = "london";
console.log(data.addresses.filter((item) => {
return item.toLowerCase().split(" ").indexOf(searchFor.toLowerCase()) != -1
}))
Related
Given the following db structure https://drawsql.app/sensor_network/diagrams/db, I would like to get all sensor_data from a certain location, while grouping the response using station.location, sensor_data.time.
I have the following query:
select
station.location_name,
sensor_data.time,
sensor.type,
sensor_data.value,
sensor.id
from station
inner join
(sensor inner join sensor_data on sensor.id = sensor_data.sensor_id)
on station.sensor_id = sensor.id
where station.location = ?
which gives me the rows I want, however, I would like to format the response in a way where all the rows which share location and time are in the same row. an example output is
location
time
type
value
id
city1
2022-01-01 08:00:00
temperature
290
1
city1
2022-01-01 09:00:00
temperature
292
1
city1
2022-01-01 08:00:00
ph
7
2
city1
2022-01-01 09:00:00
ph
8
2
which I would like to format either like (or similar to)
[
{"location": "city1", "time": "2022-01-01 08:00:00", "temperature": 290, "ph": 7},
{"location": "city1", "time": "2022-01-01 09:00:00", "temperature": 292, "ph": 8},
]
or
[
{"location": "city1", "time": "2022-01-01 08:00:00", "sensors": [{"id": 1, "type": "temperature", "value": 290}, {"id": 2, "type": "ph", "value": 7}]},
{"location": "city1", "time": "2022-01-01 09:00:00", "sensors": [{"id": 1, "type": "temperature", "value": 292}, {"id": 2, "type": "ph", "value": 8}]}
]
Currently, I am doing this formatting in javascript using array functions, but this has proven to be too slow. I have tried using group by query but to be fair, I am struggling to understand how to use that when you don't want to use methods like count etc.
I am using nodejs and its mysql package, the database is mysql:8 and tables are running with innodb engine
You can achieve this with subqueries.
SELECT
st.location,
sd.time,
(
SELECT sd2.value
FROM sensor_data sd2
INNER JOIN sensor s2
ON s2.id = sd2.sensor_id
WHERE sd2.time = sd.time
AND s2.type = "temperature"
) AS temperature,
(
SELECT sd2.value
FROM sensor_data sd2
INNER JOIN sensor s2
ON s2.id = sd2.sensor_id
WHERE sd2.time = sd.time
AND s2.type = "ph"
) AS ph
FROM station st
INNER JOIN sensor s
ON st.sensors = s.id
INNER JOIN sensor_data sd
ON s.id = sd.sensor_id
WHERE st.location = ?
GROUP BY sd.time
Obviously, this will work only if you know the list of types (temperature, ph) in advance and thus you can write separate subqueries for each of them.
If you don't want to build separate subquery for each type, you can concat the values into a single subquery column.
SELECT
st.location,
sd.time,
(
SELECT
GROUP_CONCAT(
CONCAT(s2.type, ':', sd2.value)
SEPARATOR ','
)
FROM sensor_data sd2
INNER JOIN sensor s2
ON s2.id = sd2.sensor_id
WHERE sd2.time = sd.time
GROUP BY sd2.time
) AS sensors
FROM station st
INNER JOIN sensor s
ON st.sensors = s.id
INNER JOIN sensor_data sd
ON s.id = sd.sensor_id
WHERE st.location = ?
GROUP BY sd.time;
I have 3 arrays: one with a list of cities, one with a list of states (which correspond to the cities), and one that's just a list of states with the duplicates removed.
I'm trying to generate a list that looks like this:
State 1
City 1
City 2
State 2
City 3
Here's what I've got:
$.each(stateArrayUnq, function(i) {
$('#list').append("<li>" + stateArrayUnq[i] + "<ul>");
$.each(stateArray, function(j) {
if (stateArray[j] == stateArrayUnq[i]) {
$('#list').append("<li>" + cityArray[j] + "<\/li>");
}
});
$('#list').append("<\/ul><\/li>");
});
I know I can't structure my code like this without having the browser auto-close my tags prematurely, but unfortunately I don't have the slightest idea how to rebuild this. I've read through a few related threads, but I'm still pretty confused. I think I'm supposed to set the "append" code to variables or something, but I don't know how to handle the loops.
I appreciate any help you can give. Thanks a bunch!
UPDATE: Here are my arrays:
var cityArray = ["Concord", "Lafayette", "Lewisville", "Madison", "NW Freeway Houston", "North Miami", "Casselberry", "South Fort Myers", "SW Freeway", "Woodbury", "Tarpon Springs"]
var stateArray = ["North Carolina", "Louisiana", "Texas", "Wisconsin", "Texas", "Florida", "Florida", "Florida", "Texas", "Minnesota", "Florida"]
var statearrayUnq = ["Florida", "Louisiana", "Minnesota", "North Carolina", "Texas", "Wisconsin"]
You can do this by building an html string which is stored in a variable. When you are done with your logic you can append the build html string.
//Test data
var cityArray = ["Concord", "Lafayette", "Lewisville", "Madison", "NW Freeway Houston", "North Miami", "Casselberry", "South Fort Myers", "SW Freeway", "Woodbury", "Tarpon Springs"];
var stateArray = ["North Carolina", "Louisiana", "Texas", "Wisconsin", "Texas", "Florida", "Florida", "Florida", "Texas", "Minnesota", "Florida"];
var stateArrayUnq = ["Florida", "Louisiana", "Minnesota", "North Carolina", "Texas", "Wisconsin"];
//Generate the html string and append it.
var html = "";
$.each(stateArrayUnq, function(i) {
html += "<li>" + stateArrayUnq[i] + "<ul>";
$.each(stateArray, function(j) {
if (stateArray[j] == stateArrayUnq[i]) {
html += ("<li>" + cityArray[j] + "<\/li>");
}
});
html += "<\/ul><\/li>";
});
$('#list').append(html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="list">
<p>test</p>
</div>
If list were a ul, you could nest them using actual jQuery objects like so.
var cityArray = ["Concord", "Lafayette", "Lewisville", "Madison", "NW Freeway Houston", "North Miami", "Casselberry", "South Fort Myers", "SW Freeway", "Woodbury", "Tarpon Springs"];
var stateArray = ["North Carolina", "Louisiana", "Texas", "Wisconsin", "Texas", "Florida", "Florida", "Florida", "Texas", "Minnesota", "Florida"];
var data = cityArray.map((c,i) => ({state: stateArray[i], city: c})); //flatten the data
var $list = data.reduce(($ul, item) => {
var $cityLi = $(`<li>${item.city}</li>`); //Create <li> for city
var $stateLi = $ul.children(`li[data-state='${item.state}']`); //Find state <li>
if (!$stateLi.length) //Create state <li> if it doesn't yet exist
$stateLi = $(`<li data-state='${item.state}'>${item.state}<ul></ul></li>`);
$stateLi.children("ul").append($cityLi).end().appendTo($ul); //Add the city to the state
return $ul;
}, $("<ul />"));
$("body").append($list);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I am trying to make it so that when the user clicks one of the 30 teams, the team that is clicked is queried with the Giphy API.
The giphy API key used is the public API key.
// all 30 NBA Teams //
var predefinedButtons = [
"Atlanta Hawks",
"Boston Celtics",
"Brooklyn Nets",
"Charlotte Hornets",
"Chicago Bulls",
"Cleveland Cavaliers",
"Dallas Mavericks",
"Denver Nuggets",
"Detroit Pistons",
"Golden State Warriors",
"Houston Rockets",
"Indiana Pacers",
"LA Clippers",
"LA Lakers ",
"Memphis Grizzlies",
"Miami Heat",
"Milwaukee Bucks",
"Minnesota Timberwolves",
"New Orleans Hornets",
"New York Knicks",
"Oklahoma City Thunder",
"Orlando Magic",
"Philadelphia Sixers",
"Phoenix Suns",
"Portland Trail Blazers",
"Sacramento Kings",
"San Antonio Spurs",
"Toronto Raptors",
"Utah Jazz",
"Washington Wizards"
];
console.log(predefinedButtons);
// The Buttons added dynamically //
var $nbaTeams;
var nbaButtons = function nbaGiphy() {
for ( i in predefinedButtons ) {
$nbaTeams = $("<button class='.btn btn-secondary' 'onclick='getNBAGiphy()''>").text(predefinedButtons[i]);
$("#nbaTags").append($nbaTeams);
}
}
nbaButtons();
// The code below is where the event listener is 'undefined' //
function getNBAGiphy() {
var nbaSearchGifs;
nbaSearchGifs.addEventListener('click', function() {
nbaSearchGifs = $(".btn btn-secondary").val();
xhr = $.get("http://api.giphy.com/v1/gifs/search?q="+nbaSearchGifs+"&api_key=dc6zaTOxFJmzC&limit=15");
xhr.done(function (response) {
console.log("success got data", response);
nbaTeamData = response.data
$("#giphyContent").html("");
console.log(nbaSearchGifs);
})
});
}
getNBAGiphy();
You are declaring variable and you have not assigned any value to it. So by default it is undefined. Code i am referring to is:
function getNBAGiphy() {
var nbaSearchGifs;
nbaSearchGifs.addeventListner
I am using the code below to build a table based on an API and am fine when there is in object in an array (e.g. lineStatuses[0].statusSeverityDescription), however when there is an object, in an object, in an array, it does not work and I get the result [object Object] returned.
Here is a sample of the JSON data from the URL (I am expecting Undefined to be returned for the first record):
[
{
"$type": "Tfl.Api.Presentation.Entities.Line, Tfl.Api.Presentation.Entities",
"id": "bakerloo",
"name": "Bakerloo",
"modeName": "tube",
"disruptions": [],
"created": "2016-06-03T12:36:54.19Z",
"modified": "2016-06-03T12:36:54.19Z",
"lineStatuses": [
{
"$type": "Tfl.Api.Presentation.Entities.LineStatus, Tfl.Api.Presentation.Entities",
"id": 0,
"statusSeverity": 10,
"statusSeverityDescription": "Good Service",
"created": "0001-01-01T00:00:00",
"validityPeriods": []
}
],
"routeSections": [],
"serviceTypes": [
{
"$type": "Tfl.Api.Presentation.Entities.LineServiceTypeInfo, Tfl.Api.Presentation.Entities",
"name": "Regular",
"uri": "/Line/Route?ids=Bakerloo&serviceTypes=Regular"
}
]
},
{
"$type": "Tfl.Api.Presentation.Entities.Line, Tfl.Api.Presentation.Entities",
"id": "central",
"name": "Central",
"modeName": "tube",
"disruptions": [],
"created": "2016-06-03T12:36:54.037Z",
"modified": "2016-06-03T12:36:54.037Z",
"lineStatuses": [
{
"$type": "Tfl.Api.Presentation.Entities.LineStatus, Tfl.Api.Presentation.Entities",
"id": 0,
"lineId": "central",
"statusSeverity": 5,
"statusSeverityDescription": "Part Closure",
"reason": "CENTRAL LINE: Saturday 11 and Sunday 12 June, no service between White City and Ealing Broadway / West Ruislip. This is to enable track replacement work at East Acton and Ruislip Gardens. Replacement buses operate.",
"created": "0001-01-01T00:00:00",
"validityPeriods": [
{
"$type": "Tfl.Api.Presentation.Entities.ValidityPeriod, Tfl.Api.Presentation.Entities",
"fromDate": "2016-06-11T03:30:00Z",
"toDate": "2016-06-13T01:29:00Z",
"isNow": false
}
],
"disruption": {
"$type": "Tfl.Api.Presentation.Entities.Disruption, Tfl.Api.Presentation.Entities",
"category": "PlannedWork",
"categoryDescription": "PlannedWork",
"description": "CENTRAL LINE: Saturday 11 and Sunday 12 June, no service between White City and Ealing Broadway / West Ruislip. This is to enable track replacement work at East Acton and Ruislip Gardens. Replacement buses operate.",
"additionalInfo": "Replacement buses operate as follows:Service A: White City - East Acton - North Acton - West Acton - Ealing Common (for District and Piccadilly Lines) - Ealing BroadwayService B: White City - North Acton - Northolt - South Ruislip - Ruislip Gardens - West RuislipService C: White City - North Acton - Park Royal (Piccadilly Line) - Hanger Lane - Perivale - Greenford - Northolt",
"created": "2016-05-12T11:04:00Z",
"affectedRoutes": [],
"affectedStops": [],
"isBlocking": true,
"closureText": "partClosure"
}
}
],
"routeSections": [],
"serviceTypes": [
{
"$type": "Tfl.Api.Presentation.Entities.LineServiceTypeInfo, Tfl.Api.Presentation.Entities",
"name": "Regular",
"uri": "/Line/Route?ids=Central&serviceTypes=Regular"
}
]
}
]
I am also trying to use setInterval to refresh the tube-disruption DIV with updated data from the API, which is not workng. Below is the code (with the URL returning some of the JSON data above). Any ideas what I am doing wrong?
var xmlhttp = new XMLHttpRequest();
var url = "https://api.tfl.gov.uk/line/mode/tube/status";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunctionDisruption(xmlhttp.responseText);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
setInterval(myFunctionDisruption, 600000);
function myFunctionDisruption(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].lineStatuses[0].disruption.description + <!-- DOES NOT WORK -->
"</td></tr>";
}
out += "</table>";
document.getElementById("tube-disruption").innerHTML = out;
}
The below code will generate a table for you. The generic tableMaker function takes an array of an object or an array of multiple objects provided in the first argument. All objects should have same keys (properties) since these keys are used to create the table header (if the second argument is set to true) and the values are used to create each row. It will return an HTML table text. You can see the tableMaker function working with a smaller size data at here. You can also practice it with some sample and simple data you may produce.
In your case you have multiple nested objects those, I guess, need to be converted into separate tables within the corresponding cells of the main table. For that purpose i have another function tabelizer which handles this job recursively by utilizing the tableMaker function. The result of tabelizer is a complete HTML text of your master table.
Lets see
var tableMaker = (o,h) => {var keys = o.length && Object.keys(o[0]),
rowMaker = (a,t) => a.reduce((p,c,i,a) => p + (i === a.length-1 ? "<" + t + ">" + c + "</" + t + "></tr>"
: "<" + t + ">" + c + "</" + t + ">"),"<tr>"),
rows = o.reduce((r,c) => r + rowMaker(keys.reduce((v,k) => v.concat(c[k]),[]),"td"),h ? rowMaker(keys,"th") : []);
return rows.length ? "<table>" + rows + "</table>" : "";
},
data = [
{
"$type": "Tfl.Api.Presentation.Entities.Line, Tfl.Api.Presentation.Entities",
"id": "bakerloo",
"name": "Bakerloo",
"modeName": "tube",
"disruptions": [],
"created": "2016-06-03T12:36:54.19Z",
"modified": "2016-06-03T12:36:54.19Z",
"lineStatuses": [
{
"$type": "Tfl.Api.Presentation.Entities.LineStatus, Tfl.Api.Presentation.Entities",
"id": 0,
"statusSeverity": 10,
"statusSeverityDescription": "Good Service",
"created": "0001-01-01T00:00:00",
"validityPeriods": []
}
],
"routeSections": [],
"serviceTypes": [
{
"$type": "Tfl.Api.Presentation.Entities.LineServiceTypeInfo, Tfl.Api.Presentation.Entities",
"name": "Regular",
"uri": "/Line/Route?ids=Bakerloo&serviceTypes=Regular"
}
]
},
{
"$type": "Tfl.Api.Presentation.Entities.Line, Tfl.Api.Presentation.Entities",
"id": "central",
"name": "Central",
"modeName": "tube",
"disruptions": [],
"created": "2016-06-03T12:36:54.037Z",
"modified": "2016-06-03T12:36:54.037Z",
"lineStatuses": [
{
"$type": "Tfl.Api.Presentation.Entities.LineStatus, Tfl.Api.Presentation.Entities",
"id": 0,
"lineId": "central",
"statusSeverity": 5,
"statusSeverityDescription": "Part Closure",
"reason": "CENTRAL LINE: Saturday 11 and Sunday 12 June, no service between White City and Ealing Broadway / West Ruislip. This is to enable track replacement work at East Acton and Ruislip Gardens. Replacement buses operate.",
"created": "0001-01-01T00:00:00",
"validityPeriods": [
{
"$type": "Tfl.Api.Presentation.Entities.ValidityPeriod, Tfl.Api.Presentation.Entities",
"fromDate": "2016-06-11T03:30:00Z",
"toDate": "2016-06-13T01:29:00Z",
"isNow": false
}
],
"disruption": {
"$type": "Tfl.Api.Presentation.Entities.Disruption, Tfl.Api.Presentation.Entities",
"category": "PlannedWork",
"categoryDescription": "PlannedWork",
"description": "CENTRAL LINE: Saturday 11 and Sunday 12 June, no service between White City and Ealing Broadway / West Ruislip. This is to enable track replacement work at East Acton and Ruislip Gardens. Replacement buses operate.",
"additionalInfo": "Replacement buses operate as follows:Service A: White City - East Acton - North Acton - West Acton - Ealing Common (for District and Piccadilly Lines) - Ealing BroadwayService B: White City - North Acton - Northolt - South Ruislip - Ruislip Gardens - West RuislipService C: White City - North Acton - Park Royal (Piccadilly Line) - Hanger Lane - Perivale - Greenford - Northolt",
"created": "2016-05-12T11:04:00Z",
"affectedRoutes": [],
"affectedStops": [],
"isBlocking": true,
"closureText": "partClosure"
}
}
],
"routeSections": [],
"serviceTypes": [
{
"$type": "Tfl.Api.Presentation.Entities.LineServiceTypeInfo, Tfl.Api.Presentation.Entities",
"name": "Regular",
"uri": "/Line/Route?ids=Central&serviceTypes=Regular"
}
]
}
],
tabelizer = (a) => a.length ? tableMaker(a.map(e => Object.keys(e).reduce((p,k) => (p[k] = Array.isArray(e[k]) ? tabelizer(e[k]) : e[k],p),{})),true)
: "",
tableHTML = tabelizer(data);
document.write(tableHTML);
I used arrow functions but they might not work at Safari or IE. You might need to convert them to the conventional function notation.
You can also try the code out at repl.it where you can see the HTML text displayed through console.log.
I have read through a number of Stack Overflow questions but none appear to be relevant to the problem I'm trying to solve.
I have an array of objects that I'm saving in localStorage which looks like this (this example includes just two):
[
{
"image": "http://example-image.jpg",
"restaurantName": "Elena's L'Etoile",
"parentLocation": "London",
"areaLocation": "West End of London",
"pageLink": "http://example-address1"
},
{
"image": "http://example-image2.jpg",
"restaurantName": "Pied a Terre",
"parentLocation": "London",
"areaLocation": "West End of London",
"pageLink": "http://example-address2"
}
]
Each time a user visits a page, data is pulled from the page, and a restaurant object is created which looks like this:
var restaurant = {"image": $image, "restaurantName": $restaurantName, "parentLocation": $parentLocation, "areaLocation": $areaLocation, "pageLink": $pageLink};
This is then stored pushed into the existing array of objects (above) with:
existingRestaurants.push(restaurant);
The problem is that if the user visits the same page twice, duplicate objects are pushed in the array. How can I ensure that only unique objects are pushed into the array?
Approaches I've looked into: using $.each, $.inArray, $.grep. I thought that the simplest way would be to loop through all the objects in the existingRestaurants array and compare the value of the "restaurantName" key with the corresponding value in the new restaurant object.
But I haven't been able to find anything else similar on Stack Overflow.
There's a few solutions you could use here. The first is to keep your current array of objects and scan them all for a duplicate restaurant name before inserting a new one. This would look something like this:
// assuming 'arr' is the variable holding your data
var matches = $.grep(arr, function(obj) {
return obj.restaurantName == $restaurantName;
});
if (matches.length) {
console.log('Duplicate found, item not added');
} else {
var restaurant = {
"image": $image,
"restaurantName": $restaurantName,
"parentLocation": $parentLocation,
"areaLocation": $areaLocation,
"pageLink": $pageLink
};
arr.push(restaurant);
}
Working example
Alternatively, and preferably, you could amend your data structure to be an object with the keys being the value which cannot be duplicated; in this case the restaurant names:
var arr = {
"Elena's L'Etoile": {
"image": "http://example-image.jpg",
"parentLocation": "London",
"areaLocation": "West End of London",
"pageLink": "http://example-address1"
},
"Pied a Terre": {
"image": "http://example-image2.jpg",
"parentLocation": "London",
"areaLocation": "West End of London",
"pageLink": "http://example-address2"
}
};
if (arr[$restaurantName]) {
console.log('Duplicate found, item not added');
} else {
var restaurant = {
"image": $image,
"parentLocation": $parentLocation,
"areaLocation": $areaLocation,
"pageLink": $pageLink
};
arr[$restaurantName] = restaurant;
}
Working example
How about an associative array? You'll have to select a key though:
var restaurant0 = {"image": "http://example-image.jpg", "restaurantName": "Elena's L'Etoile", "parentLocation": "London", "areaLocation": "West End of London", "pageLink": "http://example-address1" };
var restaurant1 = {"image": "http://example-image2.jpg", "restaurantName": "Pied a Terre", "parentLocation": "London", "areaLocation": "West End of London", "pageLink": "http://example-address2"};
var existingRestaurants = {};
existingRestaurants["id0"] = restaurant0;
existingRestaurants["id1"] = restaurant1;