Im trying something which is probably very easy but i cant seem to find out why its not working. Im trying to dynamically create and array with jquery/javascript.
my code;
var icons = $('.icon');
var desktopicons = [];
var user = { name: username };
var iconsetup = { myicons: [] };
desktopicons.push(user);
desktopicons.push(iconsetup);
$.each(icons, function() {
var name = $(this).attr('name');
var rel = $(this).attr('rel');
var icon = {
icon: [{
name: name,
rel: rel
}]
};
iconsetup.myicons[0].push(icon);
});
desktopicons.push(user);
desktopicons.push(iconsetup);
$('#desktop').append(desktopicons[0].name);
$('#desktop').append(desktopicons[1].myicons[0].icon[0].name);
Somehow my log file says cannot call method push of undefined on 'iconsetup.myicons[0].push(icon);' this line.
Anyone who can tell me how to create the array? Thanks!
You are using myicons[0] which means you get the first item of the myicons and that is not an array
Use
iconsetup.myicons.push(icon);
You could also simplify the whole .each() section with
iconsetup.myicons = icons.map(function(idx, item){
return {icon:[{name: item.name, rel: item.rel}]}
}).get();
You are trying to push the icon to myicons[0] which is undefined, instead you need to push to myicons which will add the icons to your array:
iconsetup.myicons.push(icon);
You never set iconsetup.myicons[0] equal to anything. iconsetup.myicons is simply an empty array with nothing in it, and no element 0. Maybe you meant:
iconsetup.myicons.push(icon);
Related
This may sound very naive, but I'm working my path through algos and need help in figuring out the traversal using DFS.
I'm getting the response from a fetch () and storing the data in an array. and using Array.shift() to get the first node from the array, pass it to the url as an id and call for another fetch() to get data related to that id.
By doing this I do reach the end of one side, however I dont know how should I go back to the root and check if there are any more children.
here is code:
data={
id: "647634",
depth: 1,
data: ["node1","node2","node3"]
}
the data for every node call look like above.
function getData(id, explored) {
var self = this;
let explored = visited && visited.length>0 ? visited : new Array();
fetch("https://test.com/id", function(data){
//here im checking if its the end child:
if (data.end) {
var end =[];
end.push(data.end); // o/p: endId: "7287382"
}else {
let s = new Array();
data.forEach(function(n){
s.push(n);
})
var t = s.shift();
explored.push(t);
self.getData(t,explored)
}
});
}
any ideas?
I'm trying to put together a web form to mark an indeterminate number of employees as either present or absent. The page itself contains an arbitrary number of divs of the form:
<div class="employee" empID="9" presence="0">
The divs themselves contain the options, with 'presence' being changed to 1 or 2 using jQuery depending on the option selected.
When the 'submit' button is pressed, I'd like to convert this data into a parsable array of pairs of 'empID' and 'presence'. I've tried doing this with jQuery as follows:
$('.cic-button').click(function(){
var submitData = {employees:[]};
$('firedrill-employee').each(function(){
submitData.push({
employeeID: $(this).attr('empID'),
presence: $(this).attr('presence')
});
});
});
However, when this is done, the submitData variable is failing to populate. Any idea why? Am I going about this in the correct manner? Is what I'm trying to do even possible?
Many thanks.
You have a few errors. Make the class that you iterate over the collection of "employee" not "firedrill-employee" and don't forget the dot to indicate it's a class. Reference the employees array withing the submitData object. You can't just push an element into an object.
$('.cic-button').click(function () {
var submitData = {
employees: []
};
$('.employee').each(function () {
submitData.employees.push({
employeeID: $(this).data('empID'),
presence: $(this).data('presence')
});
});
console.log(submitData);
});
Fiddle
Js fiddle
$('.cic-button').click(function () {
var submitData = [];
$('.employee').each(function () {
var self = $(this);
// Create and obj
var obj = new Object(); // {};
obj["employeeID"] = self.attr("empID");
obj["presence"] = self.attr("presence");
//push that object into an array
submitData.push(obj);
console.log(obj);
console.log(submitData);
});
});
You need to specify the employee array as such:
$('.cic-button').click(function(){
var submitData = {employees:[]}; // employees is an array within submitData...
$('.firedrill-employee').each(function(){
submitData.employees.push({ // ...so amend code here to push to the array, not submitData
employeeID: $(this).attr('empID'),
presence: $(this).attr('presence')
});
});
console.log(submitData);
});
See example JSFiddle - http://jsfiddle.net/yng1qb6o/
I'm facing an issue with accessing the array element in AngularJS. I have an array:
$scope.salesentry = [
{
sales_id:'',
product_id: '',
product_category_id:'',
sale_qty:null,
sale_amount:null
}
];
I want to update the sales_id field value on some button click like:
$scope.saveData = function() {
$scope.salesentry.sales_id='10';
});
I'm not able to access it in the above way. How can I do so?
salesentry is an array, so you need to access a specific element on it first using [0].
So your code becomes:
$scope.saveData = function() {
$scope.salesentry[0].sales_id='10';
});
Do you want to update each salesentry's sales_id ?
If yes you may use
angular.foreach($scope.salesentry, function(value, key){
value.sales_id = 10;
});
You need to index the array
$scope.salesentry[0].sales_id = '10'
Also, no need for the comma at the end.
Here is what im doing:
onClick, grab details immediate subnodes and publish it on html. Status = DONE // This works well
NOW, I am using a bunch of arrays to get this done.
node.eachSubnode(function(node) {
title[title.length] = node.name; // This is what i want to modify
data[data.length] = node.data; // This is what i want to modify
});
Here is how they look currently:
title = ['Coffee', 'Tea'];
data = ["Americans", "Britishers"]; // i use a loop to iterate through these arrays and append to html.
Here is what i want it to be:
var preference = {
title: 'Coffee',
data: 'Americans'
},
{
title: 'Tea',
data: 'Americans
}
I want to create this using the node.eachSubnode loop.
I'm not sure if I understood correctly, but I think this is what you want:
var preferences = [];
node.eachSubnode(function(node) {
preferences.push({
title: node.name,
data: node.data.germ
});
});
You cannot create an object that looks exactly like that, I think you need an array with objects. Assuming your node is an array with the length property, this method is the fastest.
var preference = new Array(node.length||0), i = 0;
node.eachSubnode(function(node) {
preference[i++] = {
title: node.name,
data: node.data.germ
};
});
I have an object which comes back as part of a return data from a REST server. It is part of an item object.
(I don't have control over the REST server so I can't change the data received):
{
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
}
What I want to end up with is some control over this, so that I can display the results when a product is selected in my app. It will appear in a modal. I am using Marionette/Backbone/Underscore/JQuery etc. but this is more of a JavaScript question.
I have tried multiple ways of getting at the data with no success. I would like to be able to have the options in a nested array, but I'd be open to other suggestions...
Basically this kind of structure
var Color=('Red', 'Green', 'Blue', 'Orange')
var Size('Small', 'Medium', 'Large')
The Object structure is fine, just need to be able to translate it to an array and take out the 'Option' keyword
Important to mention that I have no idea what the different options might be when I receive them - the bit after Options: might be any form of variation, color, size, flavour etc.
Loop through the parsed JSON and create new keys on a new object. That way you don't have to create the var names yourself; it's automatically done for you, albeit as keys in a new object.
var obj = {
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
}
function processObj() {
var newObj = {};
for (var k in obj) {
var key = k.split(':')[1].toLowerCase();
var values = obj[k].split(',');
newObj[key] = values;
}
return newObj;
}
var processedObj = processObj(obj);
for (var k in processedObj) {
console.log(k, processedObj[k])
// color ["Red", "Green", "Blue", "Orange"], size ["Small", "Medium", "Large"]
}
Edit: OP I've updated the code here and in the jsfiddle to show you how to loop over the new object to get the keys/values.
Fiddle.
var json = {
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
};
var color = json['Option:Color'].split(',');
var size = json['Option:Size'].split(',');
Try this to do get a solution without hardcoding all the option names into your code:
var x = {
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
};
var clean = {};
$.each(x, function(key, val){ //iterate over the options you have in your initial object
var optname = key.replace('Option:', ''); //remove the option marker
clean[optname] = val.split(","); //add an array to your object named like your option, splitted by comma
});
clean will contain the option arrays you want to create
EDIT: Okay, how you get the names of your object properties like "color", which are now the keys in your new object? Thats the same like before, basically:
$.each(clean, function(key, val){
//key is the name of your option here
//val is the array of properties for your option here
console.log(key, val);
});
Of course we stick to jQuery again. ;)