Dynamically add items to javascript object - javascript

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...

Related

Js dynamic object with dynamic arrays

Hi I am creating dynamic filter like this
Filter 1
--property 1
--property 2
--property 3
Filter 2
--property 1
--property 2
--property 3
Thats the code
var js_filter = {};
var creators_cat = [];
$('.filter-item input').on('change',function (e) {
var filter_type = $(this).attr('name');
var filter_term = $(this).val();
creators_cat.push( filter_term );
js_filter["'"+filter_type+"'"] = creators_cat;
console.log(js_filter);
})
and that's a response I get
{'filter-product_cat[]': Array(4), 'filter-brands': Array(4)}
'filter-brands': (4) ['32', '29', '23', '36']
'filter-product_cat[]': (4) ['32', '29', '23', '36']
[[Prototype]]: Object
as you can see array keys are dynamically added but values are the same for both of the keys.
An I need to add these separately.
Been looking for answer for quiet some time and didn't find something similar.
Would appreciate any help.
You shouldn't be pushing onto a global array. Each filter input should have its own array of values.
Check if there's already an element of the js_filter object for the current filter_type. If not, create it as an empty array. Then push the current value onto the array.
$('.filter-item input').on('change', function(e) {
var filter_type = $(this).attr('name');
var filter_term = $(this).val();
if (!js_filter[filter_type]) {
js_filter[filter_type] = [];
}
js_filter[filter_type].push(filter_term);
console.log(js_filter);
})

pulling data from array into new independent variables

[{…}]
0: {productName: "Powermax 125", travelSpeed: 30, materialThickness: 1, process: "125 Amps"}
length: 1
__proto__: Array(0)
Hello, This is my console output from sorting 18 sets of information like this. I have successfully sorted the list to just the entry above. now I want to store each set of information into its own variable. This is in Javascript
The Variable above is sortedList
Can someone help me make code to pull each bit of information out as a new variable?
I tried
finalProduct = sortedList.productName
finalTravelSpeed = sortedlist.travelSpeed
finalMaterialThickness= sortedList.materialThickness
finalProcess = sortedlist.process
You only make some little typos: you wrote in some cases sortedlist instead of sortedList, you didn't use camelCase-writing and you forgot the ";" and the line-end.
Because your sorted list is an array and you want the first element of it you allways have to take the first element sortedList[0] and not sortedList.
let sortedList= [{productName: "Powermax 125", travelSpeed: 30, materialThickness: 1, process: "125 Amps"}];
finalProduct = sortedList[0].productName;
finalTravelSpeed = sortedList[0].travelSpeed;
finalMaterialThickness= sortedList[0].materialThickness;
finalProcess = sortedList[0].process;
console.log (finalProduct, finalTravelSpeed, finalMaterialThickness, finalProcess);
From what i understood this is an array of objects of length 1, so first you should access index 0 of that array to get that object:
let finalProduct = sortedList[0].productName
let finalTravelSpeed = sortedlist[0].travelSpeed
let finalMaterialThickness= sortedList[0].materialThickness
let finalProcess = sortedlist[0].process
as far as i understood ! you want method to pulling
data from arrays or objects and put this data in dynamic variables have same name
var sortedList= [{productName: "Powermax 125", travelSpeed: 30, materialThickness: 1, process: "125 Amps"}];
// this function for extract objects to variables worked dynamically
function extractor_Object(obj = {}){
for(let i in obj) window[i] = obj[i];
}
extractor_Object(sortedList[0]);
console.log(productName , travelSpeed , materialThickness , process);
i hope this function help you

extending an object's parameter Javascript (Coffeescript code)

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()
})

How to add value to javascript array two time or more?

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

javascript array in array

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

Categories