I'm extracting data from as follows -
The above function returns data in the below format -
[Object { date=Date, value=112, volume=1469}, Object { date=Date, value=124, volume=539}, Object { date=Date, value=114, volume=859}, Object { date=Date, value=123, volume=1284}, Object { date=Date, value=113, volume=1382}, Object { date=Date, value=129, volume=1353}]
I would like to obtain the list of keys only as a simple array.(Parsing the first object in the array is enough to get this as all other objects have the same keys) In case of the above output, I would like the simple array to look as ["date","value","volume"]
I tried JSON.stringify & then parse but it still doesn't work.
Also, how could I convert the whole array obtained from the chart into a simple array please?
I'm visualizing an output of the below type -
[{'date':'whatever', 'value':126, 'volume':911},
{'date':'whatever', 'value':136, 'volume':1005},
{'date':'whatever', 'value':125, 'volume':720}]
If the question doesn't make sense, please let me know. I'll see how best I could re-word.
Use Object.keys() function. Here in the response from function you get an array. Use that to get the list of keys.
var data = getChartData('param')
Object.keys(data[0]);
Related
I'm trying to pass an array from my MVC Model into a javascript array (to use in fullCalendar), however having an issue.
From the below, "myArray" is being populated with the correct amount of items from the model array, but when I try to show obj.DateTime (valid field within the MVC model array) it returns undefined. The undefined alert appears the correct amount of times for items in the array.
Any help at all would be appreciated.
var myArray = [];
#foreach (var d in Model.Appointments)
{
#:myArray.push("#d");
}
myArray.forEach(function (obj) {
alert(obj.DateTime);
})
You can't use #d for converting your C# object to java-script object directly. You should encode your C# object to make a json value.
This code will encode (Serialize) your C# object to a JSON model.
#Html.Raw(Json.Encode(d));
Here is another question like yours
I am a beginner programmer trying to convert JSON array property value from arrays to keys.
From
..,"searchResult":[{"itemId":["123"],"title":["abc"],..}]
to
..,"searchResult":[{"itemId":"123","title":"abc",..}]
Full original JSON result here with search result highlighted
the JSON array is being received in this code
//function to retrieve JSON arrays
function _cb_findItemsByKeywords(root) {
//Navigates and assigns variable "items" into the property, item
var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
var a = (items);
//assigned variable a to the array
}
Question: How do I remove the square brackets and check my array a?
EDIT:
Sorry for the confusion, My goal is to combine this array with [..] with another array without [..] before appending the properties to a table.
My plan:
If I understand your question correctly, you wish to convert a JSON array into a Javascript object, since altering JSON property values to keys wouldn't be valid JSON.
To convert JSON array into Javascript object, in pure Javascript you do:
JSON.parse(yourJSONgoeshere);
Docs and examples here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
Hope it helps.
I am facing an issue that JSON.stringify not stringifies all the keys in a JSON Object.
ie. window.performance.getEntries()[0] contains around 17 keys. But on converting to a string, the result contains only 4 keys.
How can I convert all the keys in window.performance.getEntries()[0]?
I want the complete string output of window.performance.getEntries() which is an array and I used JSON.stringify(window.performance.getEntries()).
Thanks in advance..
window.performance seems to have is own toJSON-function and so can determine what will be stringified. Here is a answer and a work around to your question from a similiar question: https://stackoverflow.com/a/20511811/3400898
"If the stringify method sees an object that contains a toJSON method, it calls that method, and stringifies the value returned. This allows an object to determine its own JSON representation."
As other stated it is because there is a toJSON method defined. Basically you need to loop over every index of the array and than every property in the object.
var adjusted = window.performance.getEntries().map( function (result) {
var temp = {}, key;
for (key in result) if (key!=="toJSON") temp[key]=result[key];
return temp;
});
console.log(JSON.stringify(adjusted[0]));
The simplified solution for this problem which I found is
var jsonArray = $.map(performance.getEntries(),function(jsonObj){
var obj = $.extend({},jsonObj);
delete obj.toJSON;
return obj;
});
JSON.stringify(jsonArray);
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 am pulling an object from backbone.js and when I stringify the object I see string literal
'[{"Name":"Testname","Address":"Testaddress","id":"444444444444444"}]'
However, when I assign the non-serialized object to a variable and try to access the 0th element, I get undefined. I would expect to get object
{"Name":"Testname","Address":"Testaddress","id":"444444444444444"}
Is JavaScript not treating
[{"Name":"Testname","Address":"Testaddress","id":"444444444444444"}]
as an indexed array of objects?
To access elements of Backbone.Collection by index, use the Collection#at method:
var first = collection.at(0);
Alternatively, you can use the Collection#first method, which is actually part of the underscore library, but is proxied to Backbone collections for syntactic sugar:
var first = collection.first();
The reason you're seeing the array representation in the serialized JSON is that by convention JSON.stringify looks for a method called toJSON on the object you give to it to stringify, and if one is found, the return value of that method will be used instead. The implementation of Collection#toJSON returns a clone of the collection's internal array of models, and thus the JSON output is an array.
Just tried
var arr = JSON.parse( '[{"Name":"Testname","Address":"Testaddress","id":"444444444444444"}]' );
and
console.log( arr[0] ); // => object
What you've described should work.