how to create a custom object in javascript? - javascript

I have a javascript code like this:
var myData=[];
$.getJSON( path_url , function(data){
var len = data.rows.length;
for (var i = 0; i < len; i++){
var code = data.rows[i].codeid;
var color = data.rows[i].color;
var obj = {}
obj[code] = color
myData.push(obj);
}
console.log(myData);
});
and the results
0: Object{12: "#fc0516"},1: Object{14: "#17a030"},2: Object{31: "#17a030"}
but the results I would like this:
{12:"#fc0516",14:"#17a030",31:"#17a030"}
how can I get the result as above? sorry for my bad english, thanks in advance...

Create myData as an object, then use bracket notation to assign the property values
var myData = {};
$.getJSON(path_url, function (data) {
var len = data.rows.length;
for (var i = 0; i < len; i++) {
var code = data.rows[i].codeid;
var color = data.rows[i].color;
myData[code] = color
}
console.log(myData);
});

Related

Alternately Join 2 strings - Javascript

I have 2 strings and I need to construct the below result (could be JSON):
indexLine: "id,first,last,email\n"
dataLine: "555,John,Doe,jd#gmail.com"
Result: "id:555,first:john,....;
What would be the fastest way of joining alternately those 2 strings?
I wrote this - but it seems too straight forward:
function convertToObject(indexLine, dataLine) {
var obj = {};
var result = "";
for (var j = 0; j < dataLine.length; j++) {
obj[indexLine[j]] = dataLine[j]; /// add property to object
}
return JSON.stringify(obj); //-> String format;
}
Thanks.
var indexLine = "id,first,last,email";
var dataLine = "555,John,Doe,jd#gmail.com";
var indexes = indexLine.split(',');
var data = dataLine.split(',');
var result = [];
indexes.forEach(function (index, i) {
result.push(index + ':' + data[i]);
});
console.log(result.join(',')); // Outputs: id:555,first:John,last:Doe,email:jd#gmail.com
If you might have more than one instance of your object to create, you could use this code.
var newarray = [],
thing;
for(var y = 0; y < rows.length; y++){
thing = {};
for(var i = 0; i < columns.length; i++){
thing[columns[i]] = rows[y][i];
}
newarray.push(thing)
}
source

What is the correct way to use an Array in Javascript?

I'm new to javascript. So this question might not be good.
var arrQue = new Array(10);
for (var i = 0; i < 10; i++) {
arrQue[i] = new Array(6);
}
This code works perfectly but I wanted to know without giving the array size, how can I make something like this (the following code doesn't work):
var arrQue = new Array();//don't know the size
for (var i = 0; i < arrQue.length; i++) {
arrQue[i] = new Array();//don't know the size
}
And also the code contains two times creating new array. Is there easier or best way to do that creating multiple array?
And later I've to access like this:
arrQue[0][6] = "test";
arrQue[23][3] = "some test";
I found this method but think wrong somehow?
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
var arrQue = [];
var size = Object.size(arrQue);
for (var i = 0; i < size; i++) {
arrQue[i] = [];
var nextSize = Object.size(arrQue[i]);
}
var arrQue = [];
for (var i = 0; i < length of your inputs; i++) {
arrQue.push(input);
}
Take a look here
Check out the Array Object Methods there.. that's all the stuff you need.
You can have arrays,arrays of objects... etc..depending upon your requirement.
var arrQue = [];
for (var i = 0; i < 10; i++) {
arrQue.push(input);
}
you might be looking for the push method:
var arr = [];
arr.push(your value);

Parsing Json Array Object in specific format in javascript

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;
}

Use an array to check data

I have an array which im using to loop through divs i have stored in variables... but i want to use the values in the array as part of the variable names i wish to check.
Heres an example of what im trying to do:
var data_one = document.getElementById('test'),
data_two = document.getElementById('test2'),
array = ['one','two'];
for (var i = 0; i < array.length; i++) { //error on this line
if(parseInt(data_+array[i]) < 3){
//do something
}
}
But i get this error Uncaught ReferenceError: data_ is not defined
Is there a way to use the array values to act like the variable name some how?
What about:
var data = [
document.getElementById('test'),
document.getElementById('test2')
];
for (var i = 0; i < data.length; i++) {
if(parseInt(data[i]) < 3){
//do something
}
}
or with an object:
var data = {
'one': document.getElementById('test'),
'two': document.getElementById('test2')
};
for (var i in data) {
if(parseInt(data[i]) < 3){
//do something
}
}
Use eval which evaluates string as javascript code
var data_a = 12;
var b = "a";
alert("data_"+b); // alerts data_a
alert(eval("data_"+b)); // alerts 12
See http://jsfiddle.net/ftGhd/
var data_one = document.getElementById('test'),
data_two = document.getElementById('test2'),
array = ['one','two'];
for (var i = 0; i < array.length; i++) {
eval("var curr_array = data_"+array[i]);
if(parseInt(curr_array) < 3){
//do something
}
}

how can I parse json with multiple lines

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

Categories