I need to convert a GeoJSON output from a server to a Javascript array; I have done some searches and they were for the 'regular' JSON outputs and not the GeoJSON. Here is the output from the Server:
{"type":"FeatureCollection","features":[{"type":"Feature","property":"blah"}, {"type":"Feature","property":"blah2"}]}
And here is what I need (note, no quotation on the 'features' variable needed):
features = [{"type":"Feature","property":"blah"}, {"type":"Feature","property":"blah2"}]}
I think I need to find the 'features' property and then loop through its objects? Thanks!
A GeoJSON object is still a JSON object (it's the first thing their documentation says).
http://geojson.org/geojson-spec.html
If you want to store the features PROPERTY of a GeoJSON object, access the property value as you would normally after conversion to a javascript object and push that property into a new variable, or use as is.
var geoObject = JSON.parse(geoJSONObject);
var features = [];
features = geoObject.features;
Related
According to MDN set Method for Map, the only way for adding key/value pair to a map in javascript is a set method. I am wondering what the behavior of a map is when we add a key/value pair with a square bracket like below;
const testMap = new Map();
testMap.set( 1,"firstValue" );
testMap[2] = "secondValue";
console.log( testMap );
console.log( testMap[ 2 ] );
console.log( testMap[ '2' ] );
It seems that we can have both a map and object together! Can somebody explain this to me? I know that Map is a kind of object but this behavior can cause a lot of bugs. Is there any way to prevent this? By the way, if you add a key/value pair with square brackets, then you cannot use get method to retrieve it.
This is a special situation.
Maps are a special case that contain an entriesarray internally.
When you use the array notation, your setting key/value pairs outside this entries array.
When you use the set or get method you are actually using the internal entries array used by the map code.
The example above, essentially creates a Map object that is using the internal entries array. However, setting the second object using the array notation, means you are adding another entry/property but not in the Entries array.
Also, these values are completely different.
Do note though that these two data structures don't collide.
So testMap.get(2) is not the same variable as testMap[2].
No your example doesn't work as expected, when you use brackets, you are setting a property on the testMap object not setting an entry. You can confirm that by iterating over your map using the forEach method for example.
const testMap = new Map();
testMap.set(1, "firstValue");
testMap[2] = "secondValue";
testMap.forEach(x => console.log(x));
As you can see, there is no secondValue on the console, that is, there is no mapped entry with that value. Therefore, it wasn't added to the map what so ever.
And definetly, testMap.set(1, "firstValue"); is not equivalent to testMap[1] = "firstValue"; the only reason your are allowed to do that is because javascript permit you to add property to living objects but it is not added to the map entries.
Ref.: MDN Map
I wish to store some data dynamically in an array, using Javascript. My goal is to save a configuration, that the user has specified, and later store it in my database.
I am trying to create a array like this:
var config = [];
config.push({id:100,name:'Yashwant',age:30});
config.push({id:200,name:'Mahesh',age:35});
However, when I print out the config array, like this:
alert(config);
it prints:
[object Object],[object Object]
How can I store and push values to my array, dynamically?
EDIT:: Seems like I am storing the values correctly. How can I access it?
Alert casts the config parameter to string. If you want to see the value for debugging purposes, it is better to use console.log(config).
Or you could use JSON.stringify(config) to convert it to JSON string.
To access the values, you can do this: console.log(config[0].age, config[1].age);
If you want to print values of any javascript object you can use JSON class to either stringify object data or parse stringified data (JSON) back to object.
alert(JSON.stringify(config));
I have a variable :
var testData;
And I have a function that populates an array. Goes through an array and makes another array like so :
var person = {
"Name": obj.Name,
"Age": obj.Age,
}
partsObject.push(person);
I then want to make this array into JSON so I can use it with my D3 objects, so I do this :
testData = JSON.stringify(partsObject);
I can console log this variable, but when trying to go through it via D3's forEach method like so :
testData.forEach(function(d) // data is the JSON
{
I get the error Uncaught TypeError: testData.forEach is not a function
I don't understand how I can log the variable to the console yet it's as if I can't use it as JSON. Any ideas ?
As the name suggests stringify() converts a JavaScript object (the JSO in JSON) into a string of JSON. You can console.log() it because console.log expects to take a string, and anything that's not a string is converted to one to be displayed.
If you want to use it as an array again, you need to parse your string of JSON back to the JavaScript object: JSON.parse(testData).
You really dont need to stringify your Array to pass to d3. Do not to get confused with javascript objects, since forEach requires an array to loop through and you are passing a string to manipulate with forEach function
use:
partsObject.forEach(function(d)
{
...
JSON.stringify(partsObject); creates a string as"{'Name':'ABC','Age':23}"
Uncaught TypeError: testData.forEach is not a function caused because javascript was not able to find an Array
.stringify() turns a Javascript Object into a string. You would want to either run
partsObjects.forEach()
or alternativily you could turn the stringify'ed string back into an object with
(JSON.parse(testData)).forEach()
You are currently trying to loop through a String since you stringify your array.
Just do partsObject.forEach and don't stringify your Array.
I searched JSON and HashMap, there are many questions about "how to convert json to hashmap". So, they are different, and how can i use hashmap in js?
Short answer would be “no”, because JSON is simply a interchange format written and parsable as a JavaScript object. If you want something like a hash map, you probably would just use an Object not-so-primitive, defining and deleting keys or values respectively:
var mapObj = {};
mapObj[key] = 'value';
delete mapObj[key];
There is also the Map object that might fit such an use, new in ES6:
var mapObj = new Map();
mapObj.set('key','value');
mapObj.get('key');
mapObj.delete('key');
You can serialize JavaScript objects by calling stringify on them and then parse them again:
var stringJSON = JSON.stringify(mapObj); // check your object structure for serializability!
var objsJSON = JSON.parse(stringJSON);
Serializing a Map is a bit different. If serialisable, you can do it anyway by using Array.from() and entries():
var strMap = JSON.stringify(Array.from(mapObj.entries()));
var mapObj = new Map(JSON.parse(strMap));
Wikipedia article states clearly that JSON is just text:
[JSON] uses human-readable text to transmit data objects
JSON is stored inside strings in Javascript. Javascript objects are essentially hashmaps. You can use JSON.parse() to convert a JSON string to an object.
I know this isn't the best way to do it, but I have no other choice :(
I have to access the items in JSONObject by their index. The standard way to access objects is to just wirte this[objectName] or this.objectName. I also found a method to get all the fields inside a json object:
(for (var key in p) {
if (p.hasOwnProperty(key)) {
alert(key + " -> " + p[key]);
}
}
(Soruce : Loop through Json object).
However there is no way of accessing the JSONfields directly by a index. The only way I see right now, is to create an array, with the function above, get the fieldname by index and then get the value by fieldname.
As far as I see it, the p (in our case the JSON file must be an iteratable array to, or else the foreach loop wouldn't work. How can I access this array directly? Or is it some kind of unsorted list?
A JSON Object is more like a key-value-map; so, yes, it is unsorted. The only way to get around is the index->property name map you've already mentioned:
var keysbyindex = Object.keys(object);
for (var i=0; i<keysbyindex.length; i++)
alert(object[keysbyindex[i]]);
But why would you need these indexes? A unsorted map also has no length property, as an Array had. Why don't you use the for-in-loop
var counter = 0; // if you need it
for (var key in object) {
alert(object[key])
counter++;
}
? If you have a parsed JSON object, i.e. a plain JS Object, you won't have to worry about enumerable prototype properties.
Based on Bergis anserwer this is my solution:
var keysbyindex = Object.keys(this);
alert(this[keysbyindex[index]]);
return this[keysbyindex[index] || ""];
However, I think (not tested) it's extremly bad regaring performace and shouldn't be used! But desperate times require desperate measures.....
I don't think you can actually achieve this without creating your own parsing of JSON. You're writing that you want to go trough a JSON-object, but what you're actually trying to do is go trough a plain old Javascript object. Json is simply a string-representation used to transfer/store said object, and in here lies the main problem: the parser that transforms the string into an actual object (ie. the browser in most cases) can chose to ignore the order it finds the properties if it want to. Also, different browsers might have different approaches to parsing JSON for all you know. If they simply use a hash-map for the object that it's simple to loop through it, but the order won't be dependent on the order of the keys in the file, but rather the keys themselves.
For example, if you have the json {"b":"b","a":"a"} and do the for in loop, under some implementations you might end up with a comming first, and in others you might end up with b.
var jsn = {keyName: 'key value result come here...'};
var arr = jsn ? $.map(jsn, function (el) { return el }) : [0];
console.log(arr[0])
$('.result').text(arr[0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="result"></span>