Problem of serializing javascript object to JSON string - javascript

My question is sort of stupid that why
JSON.stringify({"annotation": [{"x":1, "y":2}, {"x":1, "y":2}]})
does not return
{"annotation": [{"x": 1, "y": 2}, {"x": 1, "y": 2}]}
but returns
{"annotation":"[{\"x\": 1, \"y\": 2}, {\"x\": 1, \"y\": 2}]"}
and how can I get the first output?

Are you using Prototype? This question may be related:
JSON.stringify() array bizarreness with Prototype.js

Related

javascript creating data object from 2 arrays [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have 2 arrays already setup within the js:
varDepth:
[0.5, 1.75, 2.38, 2.74, 2.89]
varMins:
[0, 1, 2, 3, 4]
I'm looking to create an object (chartData1) to push and this is the format of the array:
chartData1.push({'x': varDepth[i][0], 'y': varMins[i][1]});
But I cannot get this to work, I think I'm missing the setting up of the object, Any assistance would be greatly appreciated. Thanks!
Since you're trying to create multiple objects who's data are from the same indexes in both arrays; you can;
Loop over one of the arrays (I'm using map() so we can return the created objects into an array)
Add value to a new object
Add value of the other array, on the same index
const depths = [ 0.5, 1.75, 2.38, 2.74, 2.89 ];
const mins = [ 0, 1, 2, 3, 4 ];
let result = depths.map((depth, index) => ({ x: depth, y: mins[index]}))
console.log(result);
[
{
"x": 0.5,
"y": 0
},
{
"x": 1.75,
"y": 1
},
{
"x": 2.38,
"y": 2
},
{
"x": 2.74,
"y": 3
},
{
"x": 2.89,
"y": 4
}
]

sort javascript numbered keys object by property values [duplicate]

This question already has answers here:
Sorting object property by values
(44 answers)
Closed 5 years ago.
I want to sort following object by Value
var myObj = {"1": {"Value": 40}, "2": {"Value": 10}, "3": {"Value": 30}, "4": {"Value": 20}};
I tried to use sort to get keys of desired order but while making new object using it is the problem for me. I tried below method to sort:
var myObj = {"1": {"Value": 40}, "2": {"Value": 10}, "3": {"Value": 30}, "4": {"Value": 20}};
sorted = Object.keys(myObj).sort((a,b) => myObj[a].Value - myObj[b].Value).reduce((_sortedObj, key) => ({
..._sortedObj,
[key]: myObj[key]
}), {});
console.log(sorted);
Can somebody point out where am I making mistake?
Javascript Objects are not Ordered like arrays. They are key value
pairs and you can access any value in constant time by just it's key.
If you want them to be ordered then you can iterate over the properties of your object and push them in array and sort them in the order you want.
you can get something like this.
[{"Value": 10}, {"Value": 20}, {"Value": 30}, {"Value": 40}];
This is an array of Objects where each element is an object containing a key-value pair.

Array acting weird? [duplicate]

This question already has answers here:
Javascript Console Log reporting object properties incorrectly
(1 answer)
Weird behavior with objects & console.log [duplicate]
(2 answers)
Closed 5 years ago.
I've got the following code:
$(document).ready(function(){
var array = [{"x": 0}];
array[0] = {"x": 10};
console.log(array);
array[0] = {"x": 20};
console.log(array);
});
With this I expect the output in the console to be:
[
{
0: {"x": 10}
}
]
[
{
0: {"x": 20}
}
]
But instead it is:
[
{
0: {"x": 20}
}
]
[
{
0: {"x": 20}
}
]
Does anyone have any idea why? Am I missing something?
JSFiddle: https://jsfiddle.net/6nfdmt91/
try:
$(document).ready(function(){
var array = [{"x": 0}];
array[0] = {"x": 10};
console.log(array);
array[0].push({"x": 20});
console.log(array);
});
Using Array.push() will "push" a new element.

Reading CSV in D3 and converting it to array of arrays

I have the following small dataset hardcoded into a variable in my code:
var dataset = [['CENTRAL', 44, 552, 18565],
['NORTHERN', 42, 945, 20092],
['SOUTHERN', 96, 795, 30095],
['PARK', 1, 640, 9341],
['MISSION', 66, 1198, 18542],
['TENDERLOIN', 23, 113, 10735],
['RICHMOND', 9, 561, 9082],
['TARAVAL', 81, 789, 11966],
['INGLESIDE', 5, 1368, 13414],
['BAYVIEW', 7, 985, 14711]];
Now, this dataset is taken directly from a .csv file, that looks like this:
District,Prostitution,VehicleTheft,Totalcrimecount
CENTRAL,44,552,18565
NORTHERN,42,945,20092
SOUTHERN,96,795,30095
PARK,1,640,9341
MISSION,66,1198,18542
TENDERLOIN,23,113,10735
RICHMOND,9,561,9082
TARAVAL,81,789,11966
INGLESIDE,5,1368,13414
BAYVIEW,7,985,14711
However, I'd obviously like to be able to just read in the file, which I've attempted using this:
var dataset_csv = d3.csv("datafile.csv", function(d){
console.log(dataset_csv = d)
});
Which gives me an array of objects that look like this:
[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
District: "CENTRAL"
Prostitution: "44"
Totalcrimecount: "18565"
VehicleTheft: "552"
My question is, and it might be trivial, how can I transform those objects into an array data structure like my initial dataset? I've been battling with it for some time now. Any hints greatly appreciated.
Use Array#map to iterate over each object and Object.keys to catch only the keys values.
var dataset_csv = [{District: "CENTRAL", Prostitution: "44", Totalcrimecount: "18565", VehicleTheft: "552"}, {District: "WEST", Prostitution: "22", Totalcrimecount: "4324", VehicleTheft: "53"}, {District: "EAST", Prostitution: "11", Totalcrimecount: "23434" , VehicleTheft: "76"}],
datasetArr = dataset_csv.map(v => Object.keys(v).map(c => Number(v[c]) ? Number(v[c]) : v[c]));
console.log(datasetArr);

Using a variable in an JSON query

I am trying to write a function that can take a field name as an argument and return an array of corresponding values from a bit of JSON.
Example object:
var myObject = [
{"x": 10, "y": 10},
{"x": 20, "y": 10},
{"x": 20, "y": 20},
{"x": 10, "y": 20}
];
My function looks something like this:
function getValues(desiredValue) {
var values = [];
for (i = 0; i < myObject.length; i++) {
values[i] = myObject[i].desiredValue;
}
return values;
}
getValues(x);
Ideally, I would have the argument x passed to the getValues which, instead of looking for a field name called desiredValue would look for a field name called x.
The returned array should look like this:
[10,20,20,10]
As the problem with this code is obvious, how can I get the desired result?
Also, I am trying to avoid unnecessary dependencies, so please don’t give me any JQuery unless absolutely necessary.
You can use map() to return desired result.
var myObject = [
{"x": 10, "y": 10},
{"x": 20, "y": 10},
{"x": 20, "y": 20},
{"x": 10, "y": 20}
];
function getValues(desiredValue) {
return myObject.map(e => e[desiredValue]);
}
console.log(getValues('x'))
You actually need to parse the given JSON string (not the array that you have given here) by using JSON.parse(). See: http://jsbin.com/kevoqe/edit?js,console
a simple utility
//also accepts a path like "foo.bar.baz"
//returns undefined if path can't be resolved
function fetch(path){
var keys = path.split(".");
return function( target ){
for(var t = target, i = 0; i < keys.length; t = t[ keys[ i++ ] ])
if(t == null) return void 0;
return t;
}
}
and it's usage
var myObject = [
{"x": 10, "y": 10},
{"x": 20, "y": 10},
{"x": 20, "y": 20},
{"x": 10, "y": 20}
];
var result = myObject.map( fetch("y") );
this version is a bit more flexible than one hardwired with Array.map() because it can easily be composed with other functions.
Although, especially in this particular case, this already is a little bit of overkill. here you can easily write:
var result = myObject.map(pt => pt.y);
you can't get any shorter and simpler. Or if for some reason the property really is dynamic, you'll have some variable containing it:
var dynamicPropertyName = "y";
//...
var result = myObject.map(pt => pt[ dynamicPropertyName ]);
Use array map method to do manipulation in an array of objects.
Try this code :
var myObject = [
{"x": 10, "y": 10},
{"x": 20, "y": 10},
{"x": 20, "y": 20},
{"x": 10, "y": 20}
];
var output = getValues("x");
console.log(output);
function getValues(desiredValue) {
return myObject.map(function(item) {
return item[desiredValue];
});
}
Output :
Working fiddle : https://jsfiddle.net/ffyjyzjb/

Categories