I have the following array, which returns the values as follows:
0: data: (2) [10000, "Vinil s/ pó"] name: "Janeiro"
I'm trying to split this way:
var series1 = series.split(",");
var series2 = series1[1] + "," + series1[2];
But it gives me the following error:
Uncaught TypeError: series.split is not a function
Code to generate the array
var series = [],
len = data.length,
i = 0;
for(i;i<len;i++){
series.push({
name: 'Janeiro',
data:[data[i][7], data[i][3]]
});
}
Link to draw the graph Link
You don't need to split anything, your data is already in separate entries in the array, at series[index].data[0] (the number) and series[index].data[1] (the string). So you can access those in a loop, for instance:
// (`i` is already declared in the OP's code)
for (i = 0; i < series.length; ++i) {
var num = series[i].data[0];
var str = series[i].data[1];
console.log(num, str);
}
Live Example:
var data = [
[,,,"Vinil s/ pó",,,,10000],
[,,,"Another value",,,,20000],
];
var series = [],
len = data.length,
i = 0;
for(i;i<len;i++){
series.push({
name: 'Janeiro',
data:[data[i][7], data[i][3]]
});
}
// Using each entry:
for (i = 0; i < series.length; ++i) {
var num = series[i].data[0];
var str = series[i].data[1];
console.log(num, str);
}
Or with ES2015+ language features (for-of, destructuring, and const):
// Using each entry
for (const {data: [num, str]} of series) {
console.log(num, str);
}
Live Example:
var data = [
[,,,"Vinil s/ pó",,,,10000],
[,,,"Another value",,,,20000],
];
var series = [],
len = data.length,
i = 0;
for(i;i<len;i++){
series.push({
name: 'Janeiro',
data:[data[i][7], data[i][3]]
});
}
// Using each entry
for (const {data: [num, str]} of series) {
console.log(num, str);
}
Series seems to be an array of objects, since split is a String method you cant use it on arrays nor objects.
Inside each object you have the key data which points to an array so you don't have to split it in the way you seem to be trying.
Just access series[index].data[innerArrIndex]
Related
i'm actually asking myself why the following code is not working properly i found the solution but it's a bit tricky and i don't like this solution
Here is the code and the problem:
function powerSet( list ){
var set = [],
listSize = list.length,
combinationsCount = (1 << listSize),
combination;
for (var i = 1; i < combinationsCount ; i++ ){
var combination = [];
for (var j=0;j<listSize;j++){
if ((i & (1 << j))){
combination.push(list[j]);
}
}
set.push(combination);
}
return set;
}
function getDataChartSpe(map) {
var res = {};
for (var i in map) {
console.log("\n\n");
var dataSpe = {certif: false,
experience: 0,
expert: false,
grade: 1,
last: 100,
name: undefined
};
var compMatchList = [];
for (var j in map[i].comps_match) {
var tmp = map[i].comps_match[j];
compMatchList.push(tmp.name)
}
var tmpList = powerSet(compMatchList);
var lol = [];
lol.push(map[i].comps_match);
for (elem in tmpList) {
console.log("mdr elem === " + elem + " tmplist === " + tmpList);
var tmp = tmpList[elem];
dataSpe.name = tmpList[elem].join(" ");
lol[0].push(dataSpe);
}
console.log(lol);
}
return res;
}
now here is the still the same code but working well :
function powerSet( list ){
var set = [],
listSize = list.length,
combinationsCount = (1 << listSize),
combination;
for (var i = 1; i < combinationsCount ; i++ ){
var combination = [];
for (var j=0;j<listSize;j++){
if ((i & (1 << j))){
combination.push(list[j]);
}
}
set.push(combination);
}
return set;
}
function getDataChartSpe(map) {
var res = {};
var mapBis = JSON.parse(JSON.stringify(map));
for (var i in map) {
var compMatchList = [];
for (var j in map[i].comps_match) {
var tmp = map[i].comps_match[j];
compMatchList.push(tmp.name)
}
var tmpList = powerSet(compMatchList);
mapBis[i].comps_match = [];
for (elem in tmpList) {
tmpList[elem].sort();
mapBis[i].comps_match.push({certif: false,
experience: 0,
expert: false,
grade: 1,
last: 100,
name: tmpList[elem].join(", ")});
}
}
return mapBis;
}
Actually it's a bit disapointig for me because it's exactly the same but the 1st one doesn't work and the second one is working.
so if anyone can help me to understand what i'm doing wrong it'll be with pleasure
ps: i'm sorry if my english is a bit broken
In the first version, you build one dataSpe object and re-use it over and over again. Each time this runs:
lol[0].push(dataSpe);
you're pushing a reference to the same single object onto the array.
The second version of the function works because it builds a new object each time:
mapBis[i].comps_match.push({certif: false,
experience: 0,
expert: false,
grade: 1,
last: 100,
name: tmpList[elem].join(", ")});
That object literal passed to .push() will create a new, distinct object each time that code runs.
I have an element structured like this:
Element ->
[{values: arrayOfObject, key:'name1'}, ... ,{values: arrayOfObjectN, key:'nameN'}]
arrayDiObject -> [Object1, Object2, ... , ObjectN] //N = number of lines in my CSV
Object1 -> {x,y}
I have to take data from a big string:
cityX#substanceX#cityY#substanceY#
I thought to make it this way, but it seems like it pushes always in the same array of objects. If I put oggetto = {values: arrayDateValue, key: key}; inside the d3.csv function, instead if I put outside the function it add me only empty objects.
Here is my code:
var final = new Array();
var oggetto;
var key;
function creaDati() {
var newdate;
var arrayDateValue = new Array();
var selString = aggiungiElemento().split("#");
//selString is an array with selString[0]: city, selString[1]: substance and so on..
var citySelected = "";
var substanceSelected = "";
for (var i = 0; i < selString.length - 1; i++) {
if (i % 2 === 0) {
citySelected = selString[i];
} else if (i % 2 !== 0) {
substanceSelected = selString[i];
key = citySelected + "#" + substanceSelected;
d3.csv("/CSV/" + citySelected + ".csv", function(error, dataset) {
dataset.forEach(function(d) {
arrayDateValue.push({
x: d.newdate,
y: d[substanceSelected]
});
});
});
oggetto = {
values: arrayDateValue,
key: key
};
arrayDateValue = [];
final.push(oggetto);
}
}
}
Any idea ?
First you should make the if statement for the city and then for the key, which you seem to be doing wrong since you want the pair indexes to be the keys and the not pair to be the city, and you are doing the opposite. And then you need to have the d3.csv and push the objects outside of the if statement, otherwise in your case you are just adding elements with citySelected="".
Try something like :
for(var i = 0; i < selString.length -1; i+=2){
cittySelected = selString[i];
substanceSelected = selString[i+1];
key = citySelected + "#" + substanceSelected;
d3.csv("/CSV/"+citySelected+".csv", function(error, dataset){
dataset.forEach(function(d){
arrayDateValue.push({x: d.newdate, y: d[substanceSelected]});
});
});
oggetto = {values: arrayDateValue, key: key};
arrayDateValue = [];
final.push(oggetto);
}
It's is not the best way to do it, but it is clearer that what you are following, i think.
In the if(i % 2 == 0) { citySelected = ... } and else if(i % 2 !== 0) { substanceSelected = ... } citySelected and substanceSelected will never come together.
The values should be in one statement:
if(...) { citySelected = ...; substanceSelected = ...; }
The string can be splitted into pairs
city1#substance1, city2#substance2, ...
with a regex (\w{1,}#\w{1,}#).
Empty the arrayDateValue after the if-statement.
Hint:
var str = "cityX#substanceX#cityY#substanceY#";
function createArr(str) {
var obj = {};
var result = [];
var key = "";
// '', cityX#substanceX, '', cityYsubstanceY
var pairs = str.split(/(\w{1,}#\w{1,}#)/g);
for (var i = 0; i < pairs.length; i++) {
if(i % 2 !== 0) {
key = pairs[i];
// d3 stuff to create values
obj = {
// Values created with d3 placeholder
values: [{x: "x", y: "y"}],
// Pair
key: key
};
result.push(obj);
}
// Here should be values = [];
}
return result;
}
var r = createArr(str);
console.log(r);
May be you can do like this;
var str = "cityX#substanceX#cityY#substanceY",
arr = str.split("#").reduce((p,c,i,a) => i%2 === 0 ? p.concat({city:c, key:a[i+1]}) : p,[]);
console.log(JSON.stringify(arr));
RESOLVED-
The problem is about d3.csv which is a asynchronous function, it add in the array when it finish to run all the other code.
I make an XMLHttpRequest for each csv file and it works.
Hope it helps.
I want to iterate over my 'areasarray' in the array 'areas' dataprovider array,
I have no idea how to loop over an array in an array, I've tried several tries with for-loops but none of it succeeded.
this is amCharts Maps framework.
var areasarray = {};
//get JSON File
$(function getData() {
var url = "../assets/document.json";
$.ajax({
url: url,
dataType: 'json',
success: function (data) {
console.log(data);
for (var i = 0; i < data.fact.length; i++) {
if (inverseCountryCodes[data.fact[i].dims.COUNTRY] != null) {
areasarray[i] = {
"id": inverseCountryCodes[data.fact[i].dims.COUNTRY],
"value": data.fact[i].Value,
"info": "Verkeersdoden per 100 000 inwoners: " + data.fact[i].Value
}
}
}
//console.log(areasarray);
//Map initialiseren
var map;
map = new AmCharts.AmMap();
map.colorSteps = 20;
var dataProvider =
{
mapVar: AmCharts.maps.worldLow
areas: [
{
id: "BE",
value: 10,
info: "Verkeersdoden ..."
}
]
};
console.log(dataProvider);
map.areasSettings = {
autoZoom: true,
selectedColor: "#338DAB"
};
map.dataProvider = dataProvider;
var valueLegend = new AmCharts.ValueLegend();
valueLegend.right = 10;
valueLegend.minValue = "little";
valueLegend.maxValue = "a lot!";
map.valueLegend = valueLegend;
map.addListener("clickMapObject", function (event) {
document.getElementById("info").innerHTML = '<p><b>' + event.mapObject.title + '</b></p><p>' + event.mapObject.info + '</p>';
});
map.mouseWheelZoomEnabled = true;
map.write("mapdiv");
}
});
});
If you want to iterate over areasarray which is actually an object and not an array you should look into using a for...in loop
For iterating over arrays within arrays, one approach would be to nest for loops
for(var i = 0; i < array1.length; i++) {
for(var j = 0; j < array2.length; j++) {
// do something
}
}
It's not clear to me what you mean by "array in an array" in this context and it would help if you provided more information about what exactly you are trying to accomplish
I would try a nested loop. Here is an example of creating an array of arrays and then looping through each.
var matrix = []
matrix[1] = []
matrix[1][1] = "foo"
matrix.forEach(function(column){
column.forEach(function(cell){
console.log(cell);
});
});
var areasarray = {}; means it's an object, not an array.
To iterate through each items in this object, try this.
var keys = Object.keys(areasarray);
keys.forEach(function(k) {
// you can access your item using
// k is the property key
console.log(areasarray[k]);
console.log(areasarray[k].id);
console.log(areasarray[k].value);
console.log(areasarray[k].info);
});
Not sure why you chose to create areasarray as an object.
If you wanted to, you could have defined it as:
var areasarray = [];
Then when adding to the array you use:
areasarray.push({
"id": inverseCountryCodes[data.fact[i].dims.COUNTRY],
"value": data.fact[i].Value,
"info": "Verkeersdoden per 100 000 inwoners: " + data.fact[i].Value
});
So later on, you can simply do:
for (var i = 0; i < areasarray.length; i++) {
console.log(areasarray[i]);
console.log(areasarray[i].id);
console.log(areasarray[i].value);
console.log(areasarray[i].info);
}
Note: in the above code, i is an index, where in the object block code, k is a key to the object.
Use nested loops.
Example:
var a1=["1","2","3","4","5","6","7"];
var a2=["a","b","c","d","e"];
for(var i=0;i<a1.length;i++) //loop1
{
console.log(a1[i]);
for(var j=0;j<a2.length;j++) //loop2
{
console.log(a2[j]);
}
}
Sample Output:
1st iteration of loop1:
1abcde
2nd iteration of loop1:
2abcde
and so on...
For every iteration of loop1,loop2 iterates 4 times(j<5).
Hoping I got your question right...This could be an answer.!
I have a string as follows :
Panther^Pink,Green,Yellow|Dog^Hot,Top
This string means I have 2 main blocks(separated by a '|') :
"Panther" and "Dog"
Under these two main blocks, I have, lets say "subcategories".
I wanted to create a 2-dimensional array represented (in logic) as follows :
Panther(Array 1) => Pink(Element 1),Green(Element 2), Yellow(Element 3)
Dog(Array 2) => Hot(Element 1), Top(Element 2)
Also,I want to be able to add a main block, lets say "Cat" with possible categories "Cute,Proud" to the two dimensional array
I've managed to get an Array containing "Panther^Pink,Green,Yellow" and "Dog^Hot,Top" by using JavaScript's split function.
Note that this string is received via Ajax and can be of any length, though the format shown above is always used.
----------------------------- EDIT ----------------------------
Ok, my script so far is :
$(document).ready(function(){
appFunc.setNoOfAppBlock('Panther^Pink,Green,Yellow|Dog^Hot,Top');
appFunc.alertPing();
});
var appFunc = (function(stringWithSeper) {
var result = {},
i,
categories = new Array(),
subcategories;
return {
setNoOfAppBlock: function(stringWithSeper){
categories = stringWithSeper.split("|");
for (i = 0; i < categories.length; i++) {
subcategories = categories[i].split("^");
result[subcategories[0]] = subcategories[1].split(",");
}
},
alertPing: function(){
alert(result["Panther"][1]);
}
};
})();
However, the function "alertPing" isn't "alerting" anything.What am am I doing wrong ?
To me the most logical representation of your data:
Panther^Pink,Green,Yellow|Dog^Hot,Top
Is with a JavaScript object with a property for each category, each of which is an array with the subcategories:
var data = {
Panther : ["Pink", "Green", "Yellow"],
Dog : ["Hot", "Top"]
}
You would then access that by saying, e.g., data["Dog"][1] (gives "Top").
If that format is acceptable to you then you could parse it as follows:
function parseData(data) {
var result = {},
i,
categories = data.split("|"),
subcategories;
for (i = 0; i < categories.length; i++) {
subcategories = categories[i].split("^");
result[subcategories[0]] = subcategories[1].split(",");
}
return result;
}
var str = "Panther^Pink,Green,Yellow|Dog^Hot,Top";
var data = parseData(str);
Assuming you're trying to parse your data into something like this:
var result = {
Panther: ["Pink", "Green", "Yellow"],
Dog: ["Hot", "Top"]
}
you can use string.split() to break up your string into subarrays:
var str = "Panther^Pink,Green,Yellow|Dog^Hot,Top";
var result = {}, temp;
var blocks = str.split("|");
for (var i = 0; i < blocks.length; i++) {
temp = blocks[i].split("^");
result[temp[0]] = temp[1].split(",");
}
Data can then be added to that data structure like this:
result["Cat"] = ["Cute", "Proud"];
Data can be read from that data structure like this:
var dogItems = result["Dog"]; // gives you an array ["Hot", "Top"]
You can use something like:
function parseInput(_input) {
var output = [];
var parts = _input.split('|');
var part;
for(var i=0; i<parts.length; i++) {
part = parts[i].split('^');
output[part[0]] = part[1].split(',');
}
return output;
}
Calling parseInput('Panther^Pink,Green,Yellow|Dog^Hot,Top'); will return:
output [
"Panther" => [ "Pink", "Green", "Yellow" ],
"Dog" => [ "Hot", "Top" ]
]
To add another item to the list, you can use:
output["Cat"] = ["Cute", "Proud"];
I have the following array
var arr=[[10,20,30],[12,21,33],[13,23,35]];
How can I convert that array to JSON.
Desired result
myJSONarr=[
{"x":10 ,"y":20,"z":30},
{"x":12 ,"y":21,"z":33},
{"x":13, "y":23,"z":35}
];
I'm guessing I will have to define sting array
var objArray=["x","y","z"];
and do loop over these two values with the eval() function.
Any help is greatly appreciated.
if you use jquery:
var arr=[[10,20,30],[12,21,33],[13,23,35]],
myjson = JSON.stringify($.map(arr,function(a){return {x:a[0],y:a[1],z:a[2]}}));
http://jsfiddle.net/herostwist/yDRwh/
if you use prototype:
var myjson = JSON.stringify([[10,20,30],[12,21,33],[13,23,35]].map(function(a){
return {x:a[0],y:a[1],z:a[2]}}));
http://jsfiddle.net/herostwist/yDRwh/1/
My version. Edit: I didn't twig objArray wasn't part of the problem, but the OP's suggestion as part of the solution. Oh well, I like it anyway.
var arr=[[10,20,30],[12,21,33],[13,23,35]];
var objArray=["x","y","z"];
var myJSONarr = [];
for (var idx = 0; idx != arr.length; idx++) {
var row = {};
for (var idx2 = 0; idx2 != objArray.length; idx2++) {
row[objArray[idx2]] = arr[idx][idx2];
}
myJSONarr.push(row);
}
alert(JSON.stringify(myJSONarr));
Many different answers, here's another:
http://jsfiddle.net/Vecqc/
<textarea id="text" style="width: 100%;"></textarea>
var arr = [[10,20,30],[12,21,33],[13,23,35]];
var stringify = [];
for (var i = 0; i < arr.length; i++) {
stringify[i] = {'x':arr[i][0],'y':arr[i][0],'z':arr[i][0]};
}
document.getElementById('text').value = JSON.stringify(stringify);
Assuming you just want to map the values to JavaScript objects†:
var objs = [];
for(var i = 0, l = arr.length; i < l; i++) {
var p = arr[i];
objs.push({x: p[0], y: p[1], z: p[2]});
}
If you really want to create a JSON string, then you can pass this array to JSON.stringify. JSON is available in all modern browser and can be loaded for older ones.
†: Why am I assuming here? Because people confuse JSON with JavaScript object literals. In your code, myJSONarr is not JSON. It is an array of JS objects. It would be JSON if the data would be contained in a string:
var myJSONarr = '[{"x":10, "y":20, "z":30}, ...]';
JSON != JavaScript object
What you are describing is not merely a JSON conversion. You actually have an array full of three element arrays of numbers, and what you are wanting is JSON for an array of hashes where each triplet becomes a hash over "x","y","z".
Anyway, if you want a simple .toJSON() function, Prototype.js includes a .toJSON() function onto most objects that makes it really easy.
http://www.prototypejs.org/learn/json
Untested...
var arr=[[10,20,30],[12,21,33],[13,23,35]];
var myarrOfXYZ = arr.collect(function(T){ return $H({ x: T[0], y: T[1], z: T[2] }) });
var myJSON = myarrOfXYZ.toJSON();
Note that prototype also provides a function "zip" that can be used on line 2 instead of $H
Just loop through the array and create a string from each array inside it, then join the strings to form the JSON string:
var items = [];
for (var i = 0; i < arr.length; i++) {
items.push('{"x":'+arr[i][0]+',"y":'+arr[i][1]+',"z":'+arr[i][2]+'}');
}
var myJSONarr = '[' + items.join(',') + ']';
First:
var arr = [[10,20,30], [12,21,33], [13,23,35]];
var arr2 = [];
for (var i in arr) {
var a = arr[i];
arr2.push({
x: a[0],
y: a[1],
z: a[2]
});
}
Or, using higher-order functions:
var labels = ["x", "y", "z"];
var arr = [[10,20,30], [12,21,33], [13,23,35]];
var arr2 = arr.map(function(a) {
return a.reduce(function(prev, curr, i) {
prev[labels[i]] = curr;
return prev;
}, {});
});
Then directly convert the new array to JSON.