How could I create a JSON array in a javascript loop - javascript

I would like to create a javascript json array. At the and I would Like to have something like this :
var requestData= {"uris":["SampleName1", "SampleName2", "SampleName3"],"limit":100 };
The names are stored in another variable called result.results.bindings I think my for loop should be like this :
for(binding in result.results.bindings){
// binding holds SampleName1,sampleName2.. etc
}
So how could I create the array that I mentioned above?

Do you mean something like this?
var data = [];
for(binding in result.results.bindings)
data.push(binding);
var returnObject = {uris: data, limit: 100};
I do not know the structure of your data in result.results.bindings, but with the for loop you are looping over the keys of the object / array.
If you want to loop over the values and the data-source is an array you can use this:
var data = [];
result.results.bindings.forEach(function(value) {
data.push(value);
});
var returnObject = {uris: data, limit: 100};

var requestData = {};
var uris = [];
for (binding in result.results.bindings){
uris.push(binding);
}
requestData.uris = uris;
Edited as suggestion from #BenM:
var requestData = {};
requestData.uris = result.results.bindings;

I think for-in loop is not a good practice with array, It's good with object
for(var i = 0, uris = []; i < result.results.bindings.length; i++)
uris.push(result.results.bindings[i]);
var returnObject = {"uris": uris, "limit": 100};
console.log(returnObject);

var data = [];
result.results.bindings.forEach(function(value) {
eval('data.' + value + ' = ' + value);
});
// then access your variables like
alert(data.SampleName1);

Related

adding object to array using .splice()

I have a problem adding the object "myobj" to the arrays data / data2. As you see "myobj" a JS object which I would like to add to either data or data2. the functions are being triggered by clicks on different buttons.
console.log of myobj shows me
{ array: "arr_id_1", axis: "x", acc: "", vel: "", dist: "", jerk: "" }
I receive an error saying data2.splice() is not a function.
which is the format I need. "myobj" is supposed to be added to an array which I want to use JSON.stringify on. This JSON literal goes then to a python script via ajax. The array "data" is being filled with each click I perform correctly but not in the format for further processing. So I tried to fill array data2 since I have read that I could use .splice() as well. Unfortunately, console.log(data2) shows "undefined" for each field I try to fill and I have no idea how to solve it.
I tried to use JSON.stringify on "myobj" and as another attempt, I have tried to JSON.parse it back again. I tried adding the brackets and colons into quotes but no success either.
I am grateful for any advice or help.
var counterx = 0;
let data = [];
let data2 = {};
function valuesX() {
counterx++;
// does something here
let arr_id = [];
arr_id.name = 'arr_id_' + counterx;
let ind = counterx - 1;
let myobj;
function arr() {
var ind = sel.selectedIndex;
var axis = sel.options[ind].text;
arr_id.length = 0;
arr_id.push(arr_id.name, axis, btna.value, btnv.value, btns.value, btnj.value)
myobj = {
array: arr_id[0],
axis: arr_id[1],
acc: arr_id[2],
vel: arr_id[3],
dist: arr_id[4],
jerk: arr_id[5]
};
console.log(arr_id.name, arr_id)
console.log(myobj)
console.log(data.name, data)
console.log(data2.name, data2)
}
data.name = 'data';
data2.name = 'data2';
data.splice(ind, 0, arr_id)
data2.splice(ind, 0, myobj)
}
SOLUTION:
I have converted the myobj to an object using Answer from JVE999, first suggestion and used .splice() to add the every new myobj to the array data. I have used splice because I need to overwrite already existing elements while keeping the order (Thus the indx) when I trigger the function (.splice() reference).
var arr_id = [];
arr_id.name = 'arr_id_'+counterx;
var myobj;
var indx = counterx-1;
var data_new;
data.name = 'data';
function arr(){
var ind = sel.selectedIndex;
var axis = sel.options[ind].text;
arr_id.length = 0;
arr_id.push(arr_id.name, axis, btna.value, btnv.value,btns.value, btnj.value)
myobj = {
array:arr_id[0],
axis:arr_id[1],
acc:arr_id[2],
vel:arr_id[3],
dist:arr_id[4],
jerk:arr_id[5]
};
data_new = convArrToObj(myobj);
data.splice(indx, 1, data_new)
data_str = JSON.stringify(data)
console.log(data.name, data)
console.log(data_str)
}

How to put data into multi dimensional array in js inside the loop

How can we put data into multi dimensional array or json within a loop.
I know that it's possible to store multi dimensional data at one time, but I want it inside the loop as I have described in the code.
var sub_cat_checked_val = [];
sub_cat_checked.each(function (index) {
var sub_cat_id = jQuery(this).attr('name').replace('subcategory_id_', '').replace('[]', '');
sub_cat_checked_val['key_one']['key_two']='value';
sub_cat_checked_val[sub_cat_id][index] = index:jQuery(this).val();
});
As it's possible in php like $var_name['key1']['key2']['keyn']='value';
sub_cat_checked_val[sub_cat_id] needs to be defined as an array, so add the lines:
if (!sub_cat_checked_val[sub_cat_id]) {
sub_cat_checked_val[sub_cat_id] = [];
}
to define the value as an array if it does not exist.
Try this snippet:
<script>
var k = {};
k.a = {};
k.a.b = {};
k.a.b.c = {};
k.a.b.c.d = 5;
console.log(k);
</script>
I was able to do it with all of you guys help with some of modifications.
Here is what I did:
sub_cat_checked.each(function (index) {
console.log(index_val);
var sub_cat_id = jQuery(this).attr('name').replace('subcategory_id_', '').replace('[]', '');
console.log(sub_cat_id);
if (sub_cat_checked_val[sub_cat_id] == undefined) {
sub_cat_checked_val[sub_cat_id] = [];
}
sub_cat_checked_val[sub_cat_id][index] = jQuery(this).val();
});
Thanks a lot to all of you.

Create variables based on array

I have the following array and a loop fetching the keys (https://jsfiddle.net/ytm04L53/)
var i;
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
for (i = 0; i < feeds.length; i++) {
var feed = feeds[i];
alert(feed.match(/\d+$/));
}
The array will always contain different number of keys, What I would like to do is either use these keys as variables and assign the value after the : semicolon as its value or just create a new set of variables and assign the values found on these keys to them.
How can I achieve this? so that I can then perform some sort of comparison
if (test_user > 5000) {dosomething}
update
Thanks for the answers, how can I also create a set of variables and assign the array values to them? For instance something like the following.
valCount(feeds.split(","));
function valCount(t) {
if(t[0].match(/test_user_.*/))
var testUser = t[0].match(/\d+$/);
}
Obviously there is the possibility that sometimes there will only be 1 key in the array and some times 2 or 3, so t[0] won't always be test_user_
I need to somehow pass the array to a function and perform some sort of matching, if array key starts with test_user_ then grab the value and assign it to a define variable.
Thanks guys for all your help!
You can't (reasonably) create variables with dynamic names at runtime. (It is technically possible.)
Instead, you can create object properties:
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
var obj = {};
feeds.forEach(function(entry) {
var parts = entry.split(":"); // Splits the string on the :
obj[parts[0]] = parts[1]; // Creates the property
});
Now, obj["test_user_201508_20150826080829.txt"] has the value "12345".
Live Example:
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
var obj = {};
feeds.forEach(function(entry) {
var parts = entry.split(":");
obj[parts[0]] = parts[1];
});
snippet.log(obj["test_user_201508_20150826080829.txt"]);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
You can do it like this, using the split function:
var i;
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
for (i = 0; i < feeds.length; i++) {
var feed = feeds[i];
console.log(feed.split(/[:]/));
}
This outputs:
["test_user_201508_20150826080829.txt", "12345"]
["test_user_list20150826", "666"]
["test_list_Summary20150826.txt", "321"]
Use the split method
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
feedMap = {}
for (i = 0; i < feeds.length; i++) {
var temp = feeds[i].split(':');
feedMap[temp[0]] = temp[1];
}
Yields:
{
"test_user_201508_20150826080829.txt":"12345",
"test_user_list20150826":"666",
"test_list_Summary20150826.txt":"321"
}
And can be accessed like:
feedMap["test_user_201508_20150826080829.txt"]
Here is a codepen
it is not very good idea but if you really need to create variables on-the-run here's the code:
for (i = 0; i < feeds.length; i++)
{
var feed = feeds[i];
window[feed.substring(0, feed.indexOf(":"))] = feed.match(/\d+$/);
}
alert(test_user_201508_20150826080829)
Of course you cannot have any variable-name-string containing banned signs (like '.')
Regards,
MichaƂ

AngularJS Convert Array to JSON

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;

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;

Categories

Resources