I have this code:
tickets = new Object()
$(this).parents('.request-form').find('.Single').each ->
if $(this).find('.checkBoxParent input').prop('checked')
params = new Object()
params.sarId = $(this).parents('.request-form').find('.sarId').text()
params.comments = $(this).find('.commentBoxParent textarea').val()
params.serviceId = $(this).find('.serviceId').text()
tickets[$(this).parents('.categoryQuestions').find('.form-label').text()] = params
The idea is that tickets will stay empty, but as it looks through the html, it will add items and a list of sub items to it.
for example, it can find a label "classrooms" and the 3 parameters for that part of the form.
Thus I want the object to look like:
tickets[classrooms][{sarId: 1, serviceId: 3, comments: "hi"}]
Then it can find another "classroom" label and I want it to append, such that the object will now look like:
tickets[classrooms][{sarId: 1, serviceId: 3, comments: "hi"}, {sarId: 1, serviceId: 6, comments: "Another comment"}]
How can I make this happen?
switching it to a multidimensional array/object worked like this:
requestForm = $(this).parents('.request-form');
tickets = {}
requestForm.find('.Single').each ->
#alert("this should happen... 4 times")
focus = $(this)
if $(this).find('.checkBoxParent input').prop('checked')
label = $(this).parents('.categoryQuestions').find('.form-label').text()
if (!tickets.hasOwnProperty(label))
tickets[label] = []
tickets[label].push({
sarId: requestForm.find('.sarId').text(),
comments: $(this).find('.commentBoxParent textarea').val(),
serviceId: $(this).find('.serviceId').text()
})
Related
I defined this:
var data ={};
I want to get somehting like this for each "line" in the object:
{field1: "bananas", field2:'test', field3:111, field4:"23.4", field5:"bob"},
{field1: "fruit", field2:'test again', field3:222, field4:"30", field5:"john"}
I know I can do this to add dynamic and static data:
data['field1']= docType;
data['field2'] = docRef;
data['field3'] = "test3";
data['field4'] = mydynamicdata;
data['field5'] = "test5";
But how can I add different items lines? This code would only add a item set, right? How can I add a second one?
thank you!
You need an Array of Objects - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
var data = [];
data.push({field1: "bananas", field2:'test', field3:111, field4:"23.4", field5:"bob"})
data.push({field1: "fruit", field2:'test again', field3:222, field4:"30", field5:"john"})
Then you can make changes like this:
data[0]['field1'] = 'new value'
//or:
data[0].field1 = 'new value'
Where 0 is the index of the item inside of the list. So data[1] would be the second object, and so on...
This is my code, I have two array and want to put them in other array what named data:
data=[];
atIndex=0;
//userInfo is name and last name of user:
userInfo=['Mohammad','Kermani'];
//userKnow is stuff what a user know:
userKnow=['php','javascript'];
data[atIndex]=userInfo;
data[atIndex]=userInfo;
data[atIndex]=userKnow;
//I want to send data with json,and decode it with php:
console.log(data);
But now just the last data is in data
maybe it is nested array or two demential array
DEMO
You could make it an array of objects...
data[atIndex] = { userInfo: userInfo, userKnow, userKnow };
which would be accessible like so:
var userInfo = data[0].userInfo;
var userKnow = data[0].userKnow;
Your JSON would end up looking something like this (line breaks are for readability):
[
{ userInfo: ['Mohammad', 'Kermani'], userKnow: ['php', 'javascript'] }
]
Personally, if you are looking to send user information with an array of what they know then consider an object structure like this:
var userObject = {
name1: 'Mohammad',
name2: 'Kermani',
userKnow: ['php', 'javascript']
};
You can user this like so:
userObject.name1 = 'my name';// set name1
var name2 = userObject.name2;// get name2
I have a list of JS objects defined by an integer ID.
objects = [{
id: 0,
type: 'null'
}, {
id: 1,
type: 'foo'
}, {
id: 2,
type: 'bar'
}];
I implemented a function to remove an element from my list :
removeObject = function(o){
objects.splice(objects.indexOf(o), 1);
}
My problem is that I need to create a function to add a new item in my list with a id not already used (for example the lower positive integer not present in the list).
I tried to do something like that but it did not work when I remove the object 0 (for example).
addObject = function(type){
objects.push({
id: objects.length,
type: type
});
};
How can I do this ?
EDIT 1
According to your answers, I assume that the best solution in term of performance is to just use a topId which is always incremented when I add a new object in my list.
But that do not answer to my requierement. Actually I think that #X-Pippes response could be good.
Should I do someting like that :
objects = [{
id: 0,
type: 'null'
}, {
id: 1,
type: 'foo'
}, {
id: 2,
type: 'bar'
}];
// Init available ids list with the default value
availableIds = [objects.length];
removeObject = function(o){
// Remove the object from the list
objects.splice(objects.indexOf(o), 1);
// Add its id to the available ids list
availableIds.push(o.id);
}
addObject = function(type){
// Get lower id available
var newId = Math.min.apply(Math,availableIds);
// Push the new object with the id retrieved
objects.push({
id: newId,
type: type
});
// Remove used id from the available ids list
availableIds.splice(availableIds.indexOf(newId), 1);
// Add a default id if available list is empty
if(availableIds.length < 1) availableIds.push(objects.length);
};
if you remove for instance 0 and the next addObject is 0 you have to do something like:
keep a list [initial empty] with every ID removed. When you need to add a new one, pick the shorter, add and delete from list.
Also keep a var with the biggest ID added. If the previous list is empty, add +1 to the var and addObject with that id
Use the correct structures. A JavaScript object will do the job. It guarantees that you only get one item for key, you can look up and remove by key in probably O(1)ish. No point trying to re-implement it in a less efficient manner, which will be O(n) lookup.
var structure = {
objects : {},
topId : 0
}
structure.add = function(item) {
var id = this.topId ++;
structure.objects[id] = item;
}
structure.add("thing")
structure.add("other thing")
structure.add("another thing")
structure.objects
>>> Object {0: "thing", 1: "other thing", 2: "another thing"}
structure.objects[1]
>> "other thing"
Then the normal index operations to get/set/delete.
If you use that function then you have an invariant (guarantee) on your data structure that you won't use the same ID twice.
You need a function to find the first free number:
addObject = function(type){
objects.push({
id: firstOpenIndex(),
type: type
});
};
firstOpenIndex = function() {
for(var idx = 0; true; i++) {
var found = false;
for(var o in objects) {
if (objects[o].id == idx) {
found = true;
break;
}
}
if (!found) return idx;
}
}
In Javascript MaxInt is 9007199254740992. Why not just keep incrementing?
You can and probably should just use an array(s) like:
objects.type=['null','foo','bar'];
to add an object see:
How to append something to an array?
to find a value: var index = objects.type.indexOf('foo');
to find 1st empty field var index = objects.type.indexOf(''); which you can use to find the element for adding (if index is -1 use objects.type.length) if you "delete" an element by setting it to "" or... unless you have specific reason for keeping the "ID" static (in this case the array index), remove the element and only append new ones to the end
to remove an element see:
How do I remove a particular element from an array in JavaScript?
which will allow you to just push/append the next data.
if you need a new object array with empty fields to fill because you get new data to track:
object.newField=new Array(objects.type.length);
If you get to this point where your object contains multiple arrays, you will probably want to create functions for insert/add and delete/remove, so you don't do an operation on 1 and not the other.
Everything is already built in (read likely already pretty fast) and you don't need to reinvent constructors for your really cool object type.
I have something like this (data should be a global variable):
var data = {
fields:{
id: 0,
ticket: 0,
description: 0,
}
}
Now I want to use something like this to change these variables:
function toggleStatus(element) {
data[fields][element] = 1;
}
This doesn't work, of course, but what is the correct way to manipulate data in similar fashion?
Basically, I need to create a multidimensional array that changes it's status based on user input.
That should work fine, but you have to enclose fields in quotes:
data['fields'][element] = 1;
Or
data.fields[element] = 1;
if element is passed in as one of the names of the properties of field, this should work.
Try:
data['fields']['id'] = 1;
Maybe this would work?
just a note, if you're dealing with arrays of objects, it would look more like this:
var data = [{
fields:[{
id: 0,
ticket: 0,
description: "bar"
},
{
id: 1,
ticket: 1,
description: "foo"
}]
}];
then you could access the properties like
data[0].fields[0].id
data[0].fields[1].description = "more foo"
or
data[0].fields[1]['description'] = "more foo"
I am building a file management system for the web right now.
But I have some problems with javascript array's.
In the system there is an opportunity to add labels to file's.
In javascript I want to have the ID and the value's of the labels with the fileId in 1 array.(as below).
I also want the FileId and the LabelId not as the index of the array's. Because the FileId and labelId can be a realy high number. And then I have an array full of undefined items.
Here an example of how I would like to have it:
array[FileId][labelId,labelValue]
If you have an solution please help me.
Thanks.
You can form structure like this:
arr = [{FieldId:fid_value, Labels:[{labelId:lid_value, labelValue:label_text}]}]
Basically, an array with objects. Each object contains two fields: field id and labels.
Labels is an array with objects also. Each object has label id and label value property.
Code to create new items might be like this:
arr = array();
fieldObj = {FieldId:fid_value, Labels:[]};
fieldObj.Labels.push({labelId:lid_value, labelValue:label_text});
fieldObj.Labels.push({labelId:lid_value, labelValue:label_text});
fieldObj.Labels.push({labelId:lid_value, labelValue:label_text});
...
arr.push(fieldObj);
I'm not entirely sure what you're asking but array within array is possible...
a = []
a.push('a')
Result:
["a"]
a.push(['hello','world'])
Result:
["a",
Array[2]
0: "hello"
1: "world"
]
It sounds like you want objects instead of arrays:
var obj = {};
obj["fieldName"] = {label: "labelname", labelId: 1234};
Then you can access this data as:
obj["fieldName"].label
You could also use an object
var data = {};
data["item1"] = { "labelId" : "foo1", "labelValue" : "bar1" };
data["item2"] = { "labelId" : "foo2", "labelValue" : "bar2" };
console.log(data.item1.labelId);
There are plenty of ways you can strcture the object, it is normally better to use an object than to remember that index 0 is the id and that index 1 is a value.
Use should use objects as well as arrays:
var root = [{
id: '12345',
metadata: {
label: 'foo',
},
type: 'folder',
name: 'Folder Name',
children: [...]
}
];
Now, you can iterate through the folders and files in your root:
for (var i = 0; i < root.length; i++) {
var item = root[i];
console.log(item.type, item.name, item.id);
}