Use arrayvalues to access (sub)arrays - javascript

I have a page where I want to see if a certain value exists in one of the arrays I have defined, there is one main array and several "sub" arrays, they are defined like this:
var main = ['header', 'firstname', 'surname', 'tel'];
var firstname_label = ['Hank', 'Dave', 'Erin', 'Jessica'];
var surname_label = ['Michaels', 'McHankering', 'Jameson', 'Lloydd', 'Eagon', 'Philips'];
var tel_label = ['mobile', 'landline'];
I want to check the sub arrays with a variable I have, I was thinking something along these lines:
for (i=1;i<=mainCount;i++)
{
jQuery.inArray(var_x, main[i]_label)
}
Is something like this possible?

Try using an Object:
var main = ['header', 'firstname', 'surname', 'tel'];
var sub =
{
firstname_label: ['Hank', 'Dave', 'Erin', 'Jessica'],
surname_label: ['Michaels', 'McHankering', 'Jameson', 'Lloydd', 'Eagon', 'Philips'],
tel_label: ['mobile', 'landline']
};
for (i=1;i<=mainCount;i++)
{
jQuery.inArray(var_x, sub[main[i] + '_label'])
}
The alternative would be to use eval to select the variable name, but don't go there.

Related

How do I programmatically build an object from my form data that includes arrays

I need to display some values on a jsp page, grab input from user and send it back to a controller that is using Jackson to bind it to my backing data object. Several rows that I display on the screen are backed by an array and are created with <c:forEach> and I'm generating a path like "blobs[0].id" and "blobs[0].text". When I try to put them into the json object to be sent back to the controller by an ajax call, they aren't being added to the object properly. The property name ends up having "[0]" in the name instead of representing the object at that array index.
<script>
var formData = {};
formData.blobs = [];
formData.blobs[0] = {};
formData.blobs[0].id = "English";
formData.blobs[0].text = "Hello";
formData["blobs[1].id"] = "German";
formData["blobs[1].text"] = "Guten Tag";
console.log(formData);
</script>
ends up looking like {blobs: [0 : {id: "English", text: "Hello"}], blobs[1].id: "German", blobs[1].text: "Guten Tag"} instead of
{blobs: [0 : {id: "English", text: "Hello"}, 1 : {id: "German", text: "Guten Tag"}]}
I am trying to assemble the model thusly:
<script>
function createModel() {
var form = $("#theForm");
var formData = {};
$.each(form, function(i, v){
var input = $(v);
if (input.attr("name")) {
formData[input.attr("name")] = input.val();
}
});
}
</script>
Accessing obj["attr"] is an option to access an object's attribute, so obj["attr[1][22]"] will access an attribute called "attr[1][22]", while accessing obj["attr"][1][22] will access the second element of obj.attr, and the second element's 22th element as well..
The solution will be to access formData["blobs"][0].id or even formData["blobs"][0]["id"]
you can format the string to your needs
$('#yourform').serializeArray() returns an array:
[
{"name":"foo","value":"1"},
{"name":"bar","value":"xxx"},
{"name":"this","value":"hi"}
]
$('#yourform').serialize() returns a string:
"foo=1&bar=xxx&this=hi"
so, in your case
var formData = {};
formData.blobs = [];
$('#yourform').serializeArray().forEach(function(blob){
formData.blobs.push({
id: blob.name,
text: blob.value
});
})

How can I use underscore in name of dynamic object variable

Website that I'm making is in two different languages each data is saved in mongodb with prefix _nl or _en
With a url I need to be able to set up language like that:
http://localhost/en/This-Is-English-Head/This-Is-English-Sub
My code look like that:
var headPage = req.params.headPage;
var subPage = req.params.subPage;
var slug = 'name';
var slugSub = 'subPages.slug_en';
var myObject = {};
myObject[slugSub] = subPage;
myObject[slug] = headPage;
console.log(myObject);
Site.find(myObject,
function (err, pages) {
var Pages = {};
pages.forEach(function (page) {
Pages[page._id] = page;
});
console.log(Pages);
});
After console.log it I get following:
{ 'subPages.slug_en': 'This-Is-English-Sub',
name: 'This-Is-English-Head' }
Is you can see objectname subPages.slug_en is seen as a String insteed of object name..
I know that javascript does not support underscores(I guess?) but I'm still looking for a fix, otherwise i'll be forced to change all underscores in my db to different character...
Edit:
The final result of console.log need to be:
{ subPages.slug_en: 'This-Is-English-Sub',
name: 'This-Is-English-Head' }
Insteed of :
{ 'subPages.slug_en': 'This-Is-English-Sub',
name: 'This-Is-English-Head' }
Otherwise it does not work
The reason you are seeing 'subPages.slug_en' (with string quotes) is because of the . in the object key, not the underscore.
Underscores are definitely supported in object keys without quoting.
Using subPages.slug_en (without string quotes) would require you to have an object as follows:
{ subPages: {slug_en: 'This-Is-English-Sub'},
name: 'This-Is-English-Head' }
Which you could set with the following:
myObject['subPages']['slug_en'] = subPage;
Or simply:
myObject.subPages.slug_en = subPage;

How to bind two object to one in JS

I have a query filter in my code, I want to pass these two queries as one like this:
case1
con = {'eq':['case1':dosome]}
case2
con = {'eq':['case1':dosome]}
I need to bind these two at the end like this
{'eq':['case1':dosome],'eq':['case2':dosome]}
the key eq should remain same.
Why not use an object with two properties like
{ eq: { case1: dosome, case2: dosome } }
Sounds like you want an array of objects:
var your_array = new Array();
var con1 = {'eq':{'case1':dosome}}
your_array.push(con1)
var con2 = {'eq':{'case2':dosome}}
your_array.push(con2)
You can then use the methods for accessing parts of the array -> http://www.w3schools.com/js/js_array_methods.asp
Use merge() function. Also this will give error: ['case1':dosome]. Try this
<script>
var obj1 = {'eq':{'case1':dosome}};
var obj2 = {'eq':{'case2':dosome}}
var merge = obj1.merge(obj2);
</script>
Hope this helps
You can try this:
{ eq: [
{ condition: 'case1', action: doSome } ,
{ condition: 'case2', action : doSomeOther }
]}

Add [DataObject] to exsisting array with var key

Using Cordova, I am trying to get an Object to add to an array. I have this working on node JS using :
theData = {[varkey]:DataObject};
But I can't get this to work the same way within my javascript that cordova runs.
I need to do the following:
var TownName = 'Auckland', var townData = (JSON Data);
theArray = new Array();
theArray[TownName] = townData;
I need to be able to call it back as:
theArray['Auckland']
Which will return (JSON Data)
But it doesn't want to store the data with the key inside the array.
I have also tried:
theArray.TownName = townData;
theArray = [{TownName:townData}];
theArray = {[TownName]:townData}];
Nothing wants to store the data.
Any suggestions?
::EDIT::
data.theData =
"Auckland"[
{
"username":"pndemoname1",
"number":"373456",
"www":"http://373456.pndemoname1",
"icon":"/imgs/pndemoname1.png"
},
{
"username":"pndemoname2",
"number":"373458",
"www":"http://373458.pndemoname2",
"icon":"/imgs/pndemoname2.png"
}
data.town = "Auckland";
townData = new Array();
alert(JSON.stringify(data.theData))//Alerts theData
townData[data.town] = data.theData
alert(townData[townName]) //Alerts undefined
::EDIT2::
Re-defining the array within the function that deals with all of the data, seems to make it work.
As per my answer, the issue was that I assumed javascript vars are global.
Use objects or an array of objects.
A data structure like this:
{
town1: town1Data,
town2: town2Data,
}
Or more common:
[
{
name: "Town 1",
data: {...}
},
{
name: "Town 2",
data: {...}
},
]
For reference:
http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/
I got what you're trying to do, to add property names dynamically to your object is first, by making sure you are using an OBJECT instead of an array, so when you want to store something you will do the following:
var _obj = {}, _something = 'xyz';
_obj[ _something ] = { ... }; // json structure
The problem you're facing is that you want to assign a string value as a key inside your array, which will not work.
However, you can still use the array you defined and do the following:
var _array = new array();
_array.push( { .... } ); // insert json structure
Remember! By using the array you will have to loop through all values every time you want to access your key, just as the best practice to avoid getting into errors.
Good luck.
The issue was that I didn't define the array within the function of where I was trying to add the information to.
I assumed the var was global (Too much PHP)

Traverse nested maps / objects from keys in an array

I think a code sample is going to work a lot better than my vocabulary:
var keys = ['folder','name'];
var data = { folder: { name: 'Special Folder' } };
Given the two vars above, I'm looking for a way to dynamically use the array as a way to look up the object keys (sort of like a "path"). So I need to programmatically produce the following:
data['folder']['name'] // that would give me 'Special Folder'
Hopefully this makes sense, I just can't quite put all the pieces together.
TIA
var keys = ['folder','name'];
var data = { folder: { name: 'Special Folder' } };
for(var i=0;i<keys.length;i++){
data = data[keys[i]];
}
alert(data)

Categories

Resources