AngularJS Convert Array to JSON - javascript

I have an array containing 3 elements
var a = [];
a["username"]=$scope.username;
a["phoneNo"]=$scope.phoneNo;
a["altPhoneNo"]=$scope.altPhoneNo;
Now, I want to send this data to server in JSON format. Therefore, I used
var aa = JSON.stringify(a);
console.log("aa = "+aa);
But the console displays empty array
aa = []
How can I convert this array into JSON?

That's not the correct way to add elements to an array, you're adding properties instead.
If you did console.log(a.username); you'd see your $scope.username value.
You could either do
var a = [];
a.push({"username": $scope.username});
a.push({"phoneNo": $scope.phoneNo});
a.push({"altPhoneNo": $scope.altPhoneNo});
But it looks more like what you're trying to do is
var a = {};
a["username"] = $scope.username;
a["phoneNo"] = $scope.phoneNo;
a["altPhoneNo"] = $scope.altPhoneNo;
That is, you want your a to be an object if you're going to add properties to it.
And that would be better written as
var a = {};
a.username = $scope.username;
a.phoneNo = $scope.phoneNo;
a.altPhoneNo = $scope.altPhoneNo;

Related

How to add an element to multi-dimensional JSON array if the element key is a variable

There is a JSON file with an array like
{
"general_array":[
{"key_1":["a","b","c"]}
]
}
I want to add an element to the array e.g.
{"key_2":["d","e","f"]}
but the value of new key I get from a variable e.g.
var newKey = 'key_2';
I'm trying to add the element to the existed array as following
// ... getting file content
// var jsonFileContent = '{"general_array":[{"key_1":["a","b","c"]}]}';
var jsonObj = JSON.parse(jsonFileContent);
var newKey = 'key_2';
jsonObj.general_array.push({newKey:['d','e','f']});
var newJsonFileContent = JSON.stringify(jsonObj);
// and rewrite the file ...
// console.log(newJsonFileContent);
But in the file I get
{
"general_array":[
{"key_1":["a","b","c"]},
{"newKey":["d","e","f"]}
]
}
i.e. as the new element key I get the NAME of variable, but I need its VALUE
How to add the value?
UPDATED
The solution with [newKey] works in most of browsers, but it doesn't work in Internet Explorer 11
I need a solution to be working in IE11 too, so the question is still actual
You can use [newKey] to get the value of the variable as a key name:
var jsonFileContent = `
{
"general_array":[
{"key_1":["a","b","c"]}
]
}`;
var jsonObj = JSON.parse(jsonFileContent);
var newKey = 'key_2';
var tempObj = {};
tempObj[newKey] = ['d','e','f'];
jsonObj.general_array.push(tempObj);
var newJsonFileContent = JSON.stringify(jsonObj);
console.log(newJsonFileContent);
To use the value of a variable as a JSON key, enclose it in square brackets, like so:
{[newKey]:['d','e','f']}
let jsonFileContent = '{"general_array":[{"key_1":["a","b","c"]}]}';
let jsonObj = JSON.parse(jsonFileContent);
let newKey = 'key_2';
jsonObj.general_array.push({[newKey]:['d','e','f']});
let newJsonFileContent = JSON.stringify(jsonObj);
console.log(newJsonFileContent)
This is the computed property name syntax. It's a shorthand/syntax sugaring for someObject[someKey] = somevalue
Try changing this line:
jsonObj.general_array.push({newKey:['d','e','f']});
For this:
var newObj = {};
newObj[newKey] = ['d','e','f'];
jsonObj.general_array.push(newObj);

Node.js array instantiation

So, I have been trying for a while now and no luck. Currently I have an associative array as based on PSN profile data:
var PROFILE = {};
PROFILE.profileData = {};
PROFILE.titles = {};
and is used like this further down in the code:
PROFILE.profileData.onlineId = profileData.onlineId;
PROFILE.profileData.region = profileData.region;
PROFILE.titles[title.npCommunicationId] = title; //For looped, can be many
PROFILE.titles[title.npCommunicationId].trophies = {};
PROFILE.titles[title.npCommunicationId].trophies = trophyData.trophies; //any where from 10 - 50+ of these, for looped
Problem is, if I want to have multiple profiles, this doesn't work as it just inserts them in the same profile. I need 'PROFILE' to be an array that has all the above elements at each index.
PROFILEarray[n].profileData = {};
PROFILEarray[n].profileData.onlineId = profileData.onlineId;
PROFILEarray[n].profileData.region = profileData.region;
Something like this is what I need^
But for the above I get this error
Cannot read property 'profileData' of undefined
Once this is complete, it's saved into a file in JSON format to then be used by PHP code I've written to insert into a db.
This is a small snippet of the json output: http://textuploader.com/5zpbk (had to cut, too bit to upload)
you must define PROFILEarray[n] as object. JavaScript objects are containers for named values. You can not set value of undefined
PROFILEarray[n] is undefined in this case. Initialize it as {}(object)
Try this:
var PROFILEarray = [];
for (var n = 0; n < 5; n++) {
PROFILEarray[n] = {};
PROFILEarray[n].profileData = {};
PROFILEarray[n].profileData.onlineId = n;
PROFILEarray[n].profileData.region = 'Region' + n;
}
alert(JSON.stringify(PROFILEarray));

Get element in array (json format)

how can i get the first "id_miembro" for example of this:
{"actividades":[{"id_miembro":"V-005","id_dpto":"AC-04","id_actividad":"D-01","id_seccion":"S-03"},{"id_miembro":"V-005","id_dpto":"AC-02","id_actividad":"D-01","id_seccion":"S-01"}]}
I've tried with other ways but nothing, thanks.
Parsing a JSON string in javascript can be done with JSON.parse(). For your JSON you can do this to get the id_miembro of the first item in the list.
var json = '{"actividades":[{"id_miembro":"V-005","id_dpto":"AC-04","id_actividad":"D-01","id_seccion":"S-03"},{"id_miembro":"V-005","id_dpto":"AC-02","id_actividad":"D-01","id_seccion":"S-01"}]}';
var obj = JSON.parse(json);
var actividades = obj.actividades;
var first = actividades[0];
var id_miembro = first.id_miembro;
I broke it down into seperate variables so it's easier to follow which line does what.
If your data is alread a javascript object you can skip the first two lines and just do this
var obj = {"actividades":[{"id_miembro":"V-005","id_dpto":"AC-04","id_actividad":"D-01","id_seccion":"S-03"},{"id_miembro":"V-005","id_dpto":"AC-02","id_actividad":"D-01","id_seccion":"S-01"}]};
var actividades = obj.actividades;
var first = actividades[0];
var id_miembro = first.id_miembro;

Push to array a key name taken from variable

I have an array:
var pages = new Array();
I want to push my pages data to this array like this:
$('li.page').each(function () {
var datatype = $(this).attr('data-type');
var info = $(this).attr('data-info');
pages_order.push({datatype:info});
});
but this code doesn't replace datatype as variable, just puts datatype string as a key.
How do I make it place there actual string value as a key name?
I finally saw what you were trying to do:
var pages = new Array();
$('li.page').each(function () {
var datatype = $(this).attr('data-type');
var info = $(this).attr('data-info');
var temp = {};
temp[datatype] = info;
pages_order.push(temp);
});
$('li.page').each(function () {
//get type and info, then setup an object to push onto the array
var datatype = $(this).attr('data-type'),
info = $(this).attr('data-info'),
obj = {};
//now set the index and the value for the object
obj[datatype] = info;
pages_order.push(obj);
});
Notice that you can put a comma between variable declarations rather than reusing the var keyword.
It looks like you just want to store two pieces of information for each page. You can do that by pushing an array instead of an object:
pages_order.push([datatype, info]);
You have to use datatype in a context where it will be evaluated.
Like so.
var pages = [];
$('li.page').each(function () {
var datatype = $(this).attr('data-type'),
info = $(this).attr('data-info'),
record = {};
record[datatype] = info;
pages_order.push(record);
});
You only need one var it can be followed by multiple assignments that are separated by ,.
No need to use new Array just use the array literal []
You may add below single line to push value with key:
pages_order.yourkey = value;

storing data in javascript

I want to iterate through a database and store the information as an array or object.
I don't really care which as long as I can store and retrieve based on a key.
I need guidence on the syntax to use to create and store data in javascript
// create storageEntity as array or objects
storageEntity = {};
storageEntity = [];
// on each retreival from data base store data in "storageEntity"
// conceptually it should look like this:
storageEntity[recordIFromFile][recordType][dataType] = value
where:
recordIFromFile - is an numeric value from file
recordType - is a string from file
dataType - is a string from file
value - is a numeric value from the file
You want to use an object/dictionary, i.e.
var storageEntity = {};
If your ID is 99999, you'd need 99998 empty entries in an array, I guess this isn't what you want. Now if you want to store a piece of data:
var record = storageEntity[recordIFromFile];
if (record == undefined) {
record = {};
storageEntity[recordIFromFile] = record;
}
var byType = record[recordType];
if (byType == undefined) {
byType = {};
record[recordType] = byType;
}
byType[dataType] = value;
Why can't you just request a JSON from your server and work over that instead?

Categories

Resources