How to change this Javascript array format:
var sample_data = ["af","16.63","al","11.58","dz","158.97"];
to this object format:
var sample_data = {"af":"16.63","al":"11.58","dz":"158.97"};
Could use Array.shift to do it too. No idea how it compares to other methods speed wise.
var sample_data = ["af","16.63","al","11.58","dz","158.97"]; // source
var data = sample_data.slice(); // clone the data
sample_data = {};
while (data.length > 1) {
sample_data[data.shift()] = data.shift() || null;
}
var d = {}; // a temporary object
for (var i = 0; i < sample_data.length; i += 2) {
// iterate over sample_data with a step width of 2
// and set the the data in the temp. object
d[sample_data[i]] = sample_data[i+1];
}
sample_data = d;
the code for it will look like this
var sample_data = ["af","16.63","al","11.58","dz","158.97"];
var tmp = sample_data;
sample_data = {};
for (var i = 0; i < tmp.length / 2; i++)
sample_data[tmp[i * 2]] = tmp[i * 2 + 1];
EDIT
Keep in mind.
var arr = []; // This is an array
var obj = {}; // This is an object! Not array.
Related
Why is this code shown array[7][0] is undefined when it should have a value?
var tnotes = [];
var index = 0;
for (var i = 0; i < 14; i++) {
tnotes[i] = [];
}
var tx = 'B4';
var notes=['B5','A5','G5','F5','E5','D5','C5','B4','A4','G4','F4','E4','D4','C4']
var getNotes = notes.indexOf(tx);
if (getNotes != -1) {
tnotes[getNotes][index][] = new Array(20)
tnotes[getNotes][index][0] = tx //B4
tnotes[getNotes][index][2] = '3sec'
index++
}
console.log(tnotes[7][0])
You simply have a syntax error in defining one of your sub-arrays. The following line is incorrect:
tnotes[getNotes][index][] = new Array(20)
You are introducing a third-dimension of your tnotes array without it being defined
It should be:
tnotes[getNotes][index] = [];
Or if you really need the size parameter:
tnotes[getNotes][index] = new Array(20);
After this, tnotes[7][0] should no longer be undefined. Also, please do yourself a favor and make sure you use semi-colons consistently, it's good practice and can save you many-a-headache.
Corrected code:
var tnotes = [];
var index = 0;
for (var i = 0; i < 14; i++) {
tnotes[i] = [];
}
var tx = 'B4';
var notes = ['B5','A5','G5','F5','E5','D5','C5','B4','A4','G4','F4','E4','D4','C4'];
var getNotes = notes.indexOf(tx);
if (getNotes != -1) {
tnotes[getNotes][index] = [];
tnotes[getNotes][index][0] = tx; //B4
tnotes[getNotes][index][2] = '3sec';
index++;
}
console.log(tnotes[7][0]);
My JSON is:
var json = '{"name":"GeoFence","coordinate":[[1,2],[3,4],[5,6]]}',
obj = JSON.parse(json);
alert(obj.coordinate);
But i need to set the values of coordinates as follows:
var myTrip=[new google.maps.LatLng(1,2),new google.maps.LatLng(3,4),new google.maps.LatLng(5,6)];
Traverse the coordinates and create a new object for each, and add that to myTrip:
var myTrip = [];
for(var i=0; i < obj.coordinate.length; i++) {
myTrip.push(new google.maps.LatLng(obj.coordinate[i][0],obj.coordinate[i][1]))
}
How about this:
var json = '{"name":"GeoFence","coordinate":[[1,2],[3,4],[5,6]]}',
var obj = JSON.parse(json);
var myTrip = [];
for (var i = 0; i < obj.coordinate.length; i++) {
myTrip[i] = new google.maps.LatLng(obj.coordinate[i][0], obj.coordinate[i][1]);
}
You need to iterate over the collection of the coordinates:
var myTrip = getCoordinate ();
var getCoordinate = function(){
var ret = [];
for(var i = 0, length = coordinate.length; i < length; i++){
ret.push(new google.maps.LatLng(coordinate[i][0], coordinate[i][1]))
}
return ret;
}
I am trying to grab some values out of a sting that looks like this:
W1:0.687268668116, URML:0.126432054521, MH:0.125022031608, W2:0.017801539275, S3:0.00869514129605, PC1:0.00616885024382, S5L:0.0058163445156, RM1L:0.00540508783268, C2L:0.00534633687797, S4L:0.00475882733094, S2L:0.00346630632748
I want to make an array of all the keys and another array of all the values i.e. [W1, URML, MH…] and [0.687268668116, 0.126432054521...]
I have this snippet that does the trick, but only for the first value:
var foo = str.substring(str.indexOf(":") + 1);
Use split().
Demo here: http://jsfiddle.net/y9JNU/
var keys = [];
var values = [];
str.split(', ').forEach(function(pair) {
pair = pair.split(':');
keys.push(pair[0]);
values.push(pair[1]);
});
Without forEach() (IE < 9):
var keys = [];
var values = [];
var pairs = str.split(', ');
for (var i = 0, n = pairs.length; i < n; i++) {
var pair = pairs[i].split(':');
keys.push(pair[0]);
values.push(pair[1]);
};
This will give you the keys and values arrays
var keys = str.match(/\w+(?=:)/g),
values = str.match(/[\d.]+(?=,|$)/g);
RegExp visuals
/\w+(?=:)/g
/[\d.]+(?=,|$)/g
And another solution without using regexp
var pairs = str.split(" "),
keys = pairs.map(function(e) { return e.split(":")[0]; }),
values = pairs.map(function(e) { return e.split(":")[1]; });
JSFiddle
var str = "W1:0.687268668116, URML:0.126432054521, MH:0.125022031608, W2:0.017801539275, S3:0.00869514129605, PC1:0.00616885024382, S5L:0.0058163445156, RM1L:0.00540508783268, C2L:0.00534633687797, S4L:0.00475882733094, S2L:0.00346630632748";
var all = str.split(","),
arrayOne = [],
arrayTwo = [];
for (var i = 0; i < all.length; i++) {
arrayOne.push(all[i].split(':')[0]);
arrayTwo.push(all[i].split(':')[1]);
}
parse the string to an array
var str = "W1:0.687268668116, URML:0.126432054521, MH:0.125022031608, W2:0.017801539275";
var tokens = str.split(",");
var values = tokens.map(function (d) {
var i = d.indexOf(":");
return +d.substr(i + 1);
});
var keys = tokens.map(function (d) {
var i = d.indexOf(":");
return d.substr(0, i);
});
console.log(values);
console.log(keys);
http://jsfiddle.net/mjTWX/1/ here is the demo
I have the following JSON:
[{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557704","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557705","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557706","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557707","mobile":"400089151"}]
I need to extract all "phoneNumber" using a js function.
I'm testing from using html and my function is not so good:
function getNumbers(strJSON)
{
strJSON = "[{\"errorMessage\":\"success\",\"mobile\":\"400089151\",\"phoneNumber\":\"400557704\",\"returnCode\":\"0\"},{\"errorMessage\":\"success\",\"mobile\":\"400089151\",\"phoneNumber\":\"400557705\",\"returnCode\":\"0\"},{\"errorMessage\":\"success\",\"mobile\":\"400089151\",\"phoneNumber\":\"400557706\",\"returnCode\":\"0\"}]";
var len = strJSON.length;
var begin_index = strJSON.indexOf("returnCode") - 2;
var last_index = len - 1;
var string_toSplit = strJSON.substring(begin_index, last_index);
var string_splitted = string_toSplit.split("{");
var out="";
alert(strJSON);
alert("string_splitted");
alert(string_splitted);
for ( var i = 0; i < string_splitted.length; i++)
{
if (string_splitted[i].charAt(string_splitted[i].length - 1) === ",")
{
string_splitted[i] = string_splitted[i].slice(0, -1);
}
var json = "{" + string_splitted[i];
var obj = JSON.parse(json);
if (i == string_splitted.length)
{
out = out + obj.phoneNumber;
}
else
{
out = out + obj.phoneNumber + ",";
}
}
return out;
}
For modern browsers you can use the .map() method
var j = [{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557704","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557705","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557706","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557707","mobile":"400089151"}];
var phones = j.map(function(item){return item.phoneNumber});
Update
After seeing your code (do not try to manually split/parse the json string.. use the JSON.parse method) you should use
function getNumbers(strJSON)
{
var myJson = JSON.parse( strJSON );
return myJson.map(function( item ){ return item.phoneNumber}).join(',');
}
Update: An even better way:
function getNumbers(strJSON)
{
var obj = JSON.parse(strJSON);
return obj.map(x => x.phoneNumber).join(", ")
}
Original Post:
A straight forward method is to just iterate over every object in the array and take the values out individually.
var info = [{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557704","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557705","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557706","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557707","mobile":"400089151"}];
var phoneNumbers = [];
for (var i = 0; i < info.length; i++)
{
phoneNumbers.push(info[i].phoneNumber);
}
console.log(phoneNumbers);
http://jsfiddle.net/hX69r/
UPDATE:
http://jsfiddle.net/hX69r/1/
var info = [{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557704","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557705","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557706","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557707","mobile":"400089151"}];
var infoString = JSON.stringify(info); //this just turns the object array 'info' into a string
var numbers = getNumbers(infoString);
console.log(numbers);
function getNumbers(strJSON)
{
var obj = JSON.parse(strJSON);
var phoneNumbers = [];
for (var i = 0; i < obj.length; i++)
{
phoneNumbers.push(obj[i].phoneNumber);
}
return phoneNumbers.join(", ");
}
Additional Update:
var info = [{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557704","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557705","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557706","mobile":"400089151"},
{"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557707","mobile":"400089151"}];
var infoSingle = {"returnCode":"0","errorMessage":"success","Code":{},"phoneNumber":"400557704","mobile":"400089151"};
console.log(info.length); // prints 4; so you know it has the []
console.log(infoSingle.length); // prints undefined; so you know it doesn't have []
Do not try to re-invent the wheel.
There are many ways to parse JSON already:
Use JSON.parse.
Use jQuery.parseJSON
I'm having some issues with the following code:
var tmpArray = new Array();
for(var n in fnlArray){
if(fnlArray[n] == largest.val){
alert(fnlArray[n] +"-"+ largest.val);
tmpArray[n] = fnlArray[n];
}
}
fnlArray contents is:
fnlArray['result1'] = 1;
fnlArray['result2'] = 2;
fnlArray['result3'] = 2;
fnlArray['result4'] = 2;
and largest.val = 2;
The issue I'm having is the alert gets fired so I would expect to end up with tmpArray with the following:
tmpArray['result2'] = 2;
tmpArray['result3'] = 2;
tmpArray['result4'] = 2;
But the array (tmpArray) is always empty. Is this an issue with adding items to the array dynamically within a loop?
var tmpArray = new Array(); should be:
var tmpArray = {};
Your tmpArray object is not a index array, so you have to use object literals.
var tmpArray = {};
for(var n in fnlArray){
if(fnlArray[n] == largest.val){
tmpArray[n] = fnlArray[n];
}
}
alert(JSON.stringify(tmpArray)); //Prints: {"result2":2,"result3":2,"result4":2}
Demo: http://jsfiddle.net/QhFGF/