I am new to JavaScript, so please excuse my ignorance of basics and proper vocabulary.
I have a list of objects all containing specific information/variables/elements (latitde and longitude) which I would like to have in separate arrays.
var data = [{
"0": "44",
"latitude": "44",
"1": "11",
"longitude": "11"
}, {
"0": "45",
"latitude": "45",
"1": "12",
"longitude": "12"
}, {
"0": "46",
"latitude": "46",
"1": "13",
"longitude": "13"
}, {
"0": "47",
"latitude": "47",
"1": "14",
"longitude": "14"
}];
I know already that I can access specific values easily:
data[1].latitude
data[1].longitude
But how do I put them together to get something like this? :
var latitude = [44, 45, 46, 47]
var longitude = [11, 12, 13, 14]
You could loop through the elements of the data array and add the desired values to other arrays that will hold the result:
var latitudes = [];
var longitudes = [];
for (var i = 0; i < data.length; i++) {
latitudes.push(data[i].latitude);
longitudes.push(data[i].longitude);
}
// at this stage the latitudes and longitudes arrays
// will contain the desired values
Also in your data array, the latitudes and longitudes are strings whereas in your expected arrays you want integers. So you might need to parse the values using the parseInt function before adding them to the resulting arrays.
latitudes.push(parseInt(data[i].latitude, 10));
longitudes.push(parseInt(data[i].longitude, 10));
or with the parseFloat function if those strings could represent decimal numbers (which is more realistic for latitudes and longitudes).
Very similar to #Darin Dimitrov, but using .map() of array
Array.prototype.map() Creates a new array with the results of calling a provided function on
every element in this array.
Updates: It should have been like this
var lat = data.map( function(item) {
return item.latitude;
});
var lon = data.map( function(item) {
return item.longitude;
});
JSFiddle
Related
I m trying to get all the numbers from the list of all the contacts. Im probably not using forEach correctly any advice? I've put a sample of what is expected
//sample of a contact
Object {
"company": "Financial Services Inc.",
"contactType": "person",
"firstName": "Hank",
"id": "2E73EE73-C03F-4D5F-B1E8-44E85A70F170",
"imageAvailable": false,
"jobTitle": "Portfolio Manager",
"lastName": "Zakroff",
"middleName": "M.",
"name": "Hank M. Zakroff",
"phoneNumbers": Array [
Object {
"countryCode": "us",
"digits": "5557664823",
"id": "337A78CC-C90A-46AF-8D4B-6CC43251AD1A",
"label": "work",
"number": "(555) 766-4823",
},
Object {
"countryCode": "us",
"digits": "7075551854",
"id": "E998F7A3-CC3C-4CF1-BC21-A53682BC7C7A",
"label": "other",
"number": "(707) 555-1854",
},
],
},
//Expected
numbers = [
5557664823,
7075551854
]
//does not work
const numbers = contacts.map(contact => contact.phoneNumbers.forEach(number));
forEach always returns undefined, so your map callback returns undefined, so numbers will be full of undefineds.
I think you probably want to return the phone numbers (each number in the phoneNumbers array of each entry), and then perhaps flatten the result:
const numbers = contacts.map(contact => contact.phoneNumbers.map(({number}) => number)).flat();
Array.prototype.flat is relatively new, but easily polyfilled.
That's such a common pattern that there's a flatMap method to do it in one go:
const numbers = contacts.flatMap(contact => contact.phoneNumbers.map(({number}) => number));
Or just a simple loop with push:
const numbers = [];
for (const {phoneNumbers} of contacts) {
numbesr.push(...phoneNumbers.map(({number}) => number));
}
Probably want to use reduce and map
let numbers = contacts.reduce((p, c, i) => {
return p.concat(c.phoneNumbers.map(pn => pn.number));
}, []);
I don't know how many times I've done that. forEach doesn't return anything.
const numbers = contacts.reduce((n, c)=>(a.concat(contact.phoneNumbers)),[]);
or
const numbers = contacts.reduce((n, c)=>(a.concat(contact.phoneNumbers.map(pn=>pn.number)),[]);
I want to convert the following string to an array
[{id: "1", type: "railroadCrossingSign", latitude: "55.647432", longtitude: "12.187673"}, {id: "2", type: "stationSign", latitude: "55.647444", longtitude: "12.187545"}]
Unfortunately an error occurs when I am JSON.parse(), probably because of the objects in the string...
How do i convert a JSON string with objects to an array with objects?
JSON format requires that your keys also must be wrapped into "".
var string = '[{"id": "1", "type": "railroadCrossingSign", "latitude": "55.647432", "longtitude": "12.187673"}, {"id": "2", "type": "stationSign", "latitude": "55.647444", "longtitude": "12.187545"}]';
var arr = JSON.parse(string);
console.log(arr);
In order to achieve what you want. Your JSON key value pair must in a string format too.
Say,
var obj = '[{
"key" : "value"
}]';
Finally, when you use:
var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;
You get the following results:
John, 30
Some observations :
First make sure your JSON should be a valid JSON.
Object properties should be wrapped into quotes "".
If your JSON is already an JSON Object then no need to parse it again otherwise it will throw an error.
var jsonObj = [{
"id": "1",
"type": "railroadCrossingSign",
"latitude": "55.647432",
"longtitude": "12.187673"
}, {
"id": "2",
"type": "stationSign",
"latitude": "55.647444",
"longtitude": "12.187545"
}];
var newObj = JSON.parse(jsonObj);
console.log(newObj); // Error : Uncaught SyntaxError: Unexpected token o in JSON at position 1
I have this normal array
["Company="Google",Country="USA",Id="123"", "Company="Volvo",Country="SWEDEN",Id="999""]
And I would like to build an object out of its values.
Expected result is
{
"root": [{
"Company": "Google",
"Country": "USA",
"Id": "123"
}, {
"Company": "Volvo",
"Country": "SWEDEN",
"Id": "999"
}
]
}
How do I work this structure in JavaScript?
the array you posted is not valid we'll need to mix single and double quotes like this:
['Company="Google",Country="USA",Id="123"', 'Company="Volvo",Country="SWEDEN",Id="999"']
if you're getting the array as a response from a request and you copied it from console than it quotes must've been escaped using \" and you don't have to fix it.
converting the array into an object:
var myArray = ['Company="Google",Country="USA",Id="123"', 'Company="Volvo",Country="SWEDEN",Id="999"']
var myObject = array2obj(myArray);
function array2obj(myArr) {
var myObj = {root:[]}
myArr.forEach(function(v) {
var currentObj = {}
v.split(",").forEach(function(vi) {
var tmp = vi.replace(/\"/g, "").split("=");
currentObj[tmp[0]] = tmp[1];
});
myObj.root.push(currentObj);
});
return myObj
}
as you can see you call the function like this var myObject = array2obj(myArray) assuming your array is stored in myArray.
now you have your object in the variable myObject:
{
"root": [
{
"Company": "Google",
"Country": "USA",
"Id": "123"
},
{
"Company": "Volvo",
"Country": "SWEDEN",
"Id": "999"
}
]
}
"reducing" the array into ids only:
as asked in comments, the following will produce a newArray = ["123", "999"]
var myArray = ['Company="Google",Country="USA",Id="123"', 'Company="Volvo",Country="SWEDEN",Id="999"'];
var newArray = myArray.map(function(x) {
var id = /,\s*id\s*=\s*"(.*?)"/gi.exec(x);
if (id) return id[1]
});
I'm using regex to match the id and .map() to create a new array with the matched results.
if you want the array to contain numbers and not strings replace return id[1] with return Number(id[1]) but you have to make sure ids are always numbers or you will get NaN errors
when my ajax call completes an array of json is returned
for my angular data binding to work perfectly, i need to merge all values in to a single JSON file. I have tried $.extend(), it's giving following output
Need a solution for this
for example if my response looks like this:
[0:"{'test':'test'}", 1:"{'test':'test'}", 2:"{'test':'test'}",3: "{'test':'test'}"];
the output i need is :
{ test':'test', 'test':'test', 'test':'test', 'test':'test' }
Edit:
The final value will be associated to the ng-model automatically.
desired output example:
{
"unique_id": 172,
"portfolio": "DIGITAL",
"bus_unit": "dummy",
"project_phase": "",
"test_phase": "SIT",
"project": "Google",
"golivedate": "03/09/2016",
"performance": "Green",
"summary": "jgnbfklgnflknflk",
"last_updated": "",
"risks_issues": "gfmngfnfglkj",
"project_start": "03/16/2016",
"batchLast_run": "",
"custom_project": "1",
"test_execution_id": 5456,
"unique_id": 172,
"test_execution_id": 5456,
"pass": 8,
"fail": 8,
"blocked": 8,
"in_progress": 8,
"no_run": 8,
"not_available": 0,
"total": 8
}
From what I understand you are trying to convert array of Json data into one singel json data. So you have array of values but you would want all of them in one variable. Try this
var testData = ["{'test':'test'}", "{'test':'test'}", "{'test':'test'}", "{'test':'test'}"];
var finalData ="";
$.each(testData,function(index,value){
finalData += value +',';
});
finalData = finalData.replace(/\},\{/g,',').slice(0, -1);
document.write(finalData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Map just applies the function to every element in the array.
var arrayOfJSON = ...
var arrayOfObjects = arrayOfJSON.map(function (jsonString){
return JSON.parse(jsonString)
})
var jsonStringWithAllObjects = JSON.stringify(arrayOfObjects)
If you use underscore.js then can easily
like:
var list = [{"test1": "test1"}, {"test2": "test2"}, {"test3": "test3"}];
var newList = _.extend.apply(null,[{}].concat(list));
then output will be
{ test1: "test1", test2: "test2", test3: "test3" }
Iterate over the array, convert every value to a JSON object, concatenate and then convert to a string back.
If you need fo this more times, you probably should make this a function.
I am attempting to create a Google map with data from two separate json files. I'm trying to use jquery/javascript to combine the two files and then process the resulting array of objects through the Google Maps API.
I've tried $.extend, $.merge, concat, and I've even tried pushing the data into an empty array, but in each case only the first set of data is appearing on the map (although I can see both sets of data separately if I display them with console.log).
I must be doing something fundamentally wrong, but I'm not seeing it. The relevant part of my code is as follows (with the things I've tried commented out). Any suggestions would be most appreciated.
j$.when(
j$.getJSON('mapData1.js'),
j$.getJSON('mapData2.js')
).done(function(data1, data2) {
var d1 = data1;
var d2 = data2;
var d3 = [];
d3.push(d1[0]);
d3.push(d2[0]);
//var d3 = j$.extend({},d1,d2);
//var d3 = j$.merge(d1,d2);
//var d3 = d1.concat(d2);
var data = d3[0];
//code to process data with Google Maps API
});
My json files look like this (but with many more items):
[
{
"ID": "a001a000002o4iZAAQ",
"NAME": "Atlanta",
"Address": "123 State Street",
"City": "Atlanta",
"StateAbbreviation": "GA",
"SF": "",
"LeaseExpiration": "8/31/2012",
"Occupancy": "2",
"Country": "USA",
"Address2": "",
"Lat": "33.7863317",
"Lng": "-84.3836873",
"Type": "loc",
"Color": "red"
}
]
you can use concat()
var array1 = [{
"ID-1": "a001a000002o4iZAAQ",
"NAME-1": "Atlanta",
"Address-1": "123 State Street",
"City-1": "Atlanta",
"StateAbbreviation-1": "GA",
"SF-1": "",
"LeaseExpiration-1": "8/31/2012",
"Occupancy-1": "2",
"Country-1": "USA",
"Address2-1": "",
"Lat-1": "33.7863317",
"Lng-1": "-84.3836873",
"Type-1": "loc",
"Color-1": "red"
}];
var array2 = [{
"ID-2": "a001a000002o4iZAAQ",
"NAME-2": "Atlanta",
"Address-2": "123 State Street",
"City-2": "Atlanta",
"StateAbbreviation-2": "GA",
"SF-2": "",
"LeaseExpiration-2": "8/31/2012",
"Occupancy-2": "2",
"Country-2": "USA",
"Address2-2": "",
"Lat-2": "33.7863317",
"Lng-2": "-84.3836873",
"Type-2": "loc",
"Color-2": "red"
}];
var array3 = array1.concat(array2);
alert(JSON.stringify(array3));