Reference javascript array inside click function by dynamically creating the array name - javascript

So I have an array something like this:
var first_array = ['foo','bar','foobar'];
I am running a click function and trying to get the name of the array and loop through the array which has first as the ID name something like this
$('element').on('click',function(){
var id = $(this).attr('id');
var arr = id+"_array";
$.each(arr,function(index,value){
console.log(value);
})
})
Now the arr gives a variable name first_array and not the array. Hence the each loop fails. Is there a way to reference the array? I need to dynamically create the array variable name and get the array elements. I have also tried declaring the array globally and inside the click function but does not work.

Like Rayon Dabre said in the comments, you should use a parent object containing your first_array, and more, like that :
var parent_array = {
first_array: ['foo','bar','foobar'],
second_array: ['foo2', 'bar2', 'foobar2']
};
$('element').on('click',function(){
var id = $(this).attr('id');
var arr = parent_array[id+"_array"];
$.each(arr,function(index,value){
console.log(value);
})
});

You can put all your arrays into a javascript object or a parent array and access them by key/name like parentArr["first_array"]

Related

Create javascript object dynamic in a foreach loop

I want to create objects in a foreach loop:
I'm starting from this:
data.forEach(function (el) {
var dynamic_var = new Quill(el['editor']);
dynamic_var.on('text-change', logHtmlContent);})
But, dynamic_var is 'overwritten', and I want to remain unique.
I check some html elements, and for each one that I found I want to create a new Object, and execute the Object methods.
In my case the variable get a new object per each iteration, is not a new variable.
Is this what you were looking for?
var quillValueContainer = {};
// ...
data.forEach(function(el) {
quillValueContainer[el] = new Quill(el['editor']);
quillValueContainer[el].on('text-change', logHtmlContent);
});
This will only work if el is a string, or number. Seeing how you are using it like this: el['editor'], makes me thing it's an Object, in which case, you can instead use the indices of the elements.
var quillValueContainer = {}; // [] should also work for indexes
// ...
data.forEach(function(el, index) {
quillValueContainer[index] = new Quill(el['editor']);
quillValueContainer[index].on('text-change', logHtmlContent);
});
Also, I don't know if this is something you need to do, but you can check if the Quill Object has already been initialized and skipping a duplication if it has, by doing:
data.filter(function(el, index){ return !quillValueContainer[index]; }).foreach(...
Or
data.forEach(function(el, index) {
if(quillValueContainer[index]) return;
quillValueContainer[index] = new Quill(el['editor']);
quillValueContainer[index].on('text-change', logHtmlContent);
});

Is it possible to break an "each" iteration, append or add something to one of the values and then continue?

Is it possible to break an "each" iteration, append or add something to one of the values and then continue?
var aKeys = new Array(),
aValues = new Array(),
sArray = {};
$(input).each(function (index, element) {
var sKey = $(this).attr('name'),
sValue = $(this).val();
aKeys.push(sKey);
aValues.push(sValue);
});
As you can see, I'm first creating a few arrays and an empty object named "sArray". Then I'm pushing the values inside those arrays via input attributes. Finally, I'm creating my object:
aKeys.forEach(function (v, j) {
sArray[v] = aValues[j];
});
return sArray;
But here's the thing. I want to add a nested object inside one of those values. I already have that object stored in another variable. Is there a way to append it or add it?
EDIT:
I've been looking at the examples and maybe I didn't express myself quite well. I've already created an object. What I wanna do is to append or store another object inside one of the keys of this object I've created.
sArray is an object, not an array. You don't need the arrays ata ll to build the object. Try this...
var sObj = {};
$("input").each(function (index, element) {
sObj[$(this).attr('name')] = $(this).val();
});
// Let's nest another object in there i guess...
var myObj = {"wut-wut": "in the butt"};
sObj.pickles = myObj;
console.log(sObj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name=one value=1>
<input name=two value=2>
<input name=three value=3>
<input name=four value=4>

create array in reverse order

I've got buttons with a common class (buttons). How can I add their IDs in to an array in a reverse order?
var yourArray = [];
$('.buttons').each(function() {
yourArray.push( $(this).prop('id') );
});
You could create the array by adding each element to the beginning of the array using unshift():
var yourArray = [];
$('.buttons').each(function() {
yourArray.unshift(this.id);
});
Alternatively you can create it in the current order and then reverse() it. Also note that you can use map() to create the array initially:
var yourArray = $('.buttons').map(function() {
return this.id;
}).get().reverse();
Finally you can use this.id instead of creating a jQuery object just to access a property already accessible without the need of object creation.
You can do something simple with map() and reverse()
var yourArray = $('.buttons').map(function() {
return this.id; // get the id
})
.get() // get the array
.reverse(); // reverse the array
console.log(yourArray);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="a" class="buttons"></button>
<button id="b" class="buttons"></button>

How to create array with variables?

I have an svg map with several points where I want to store the initial position of each point in an array. And each point has it's own ID, like point_1, point_2 etc.
I have attached a click handler to each of these and run a function when they are clicked.
So what I want to do in this function is to check if the array already contains the information of the clicked element. If it doesn't, I want to create it.
This is what I want to do, in pseudo code
var arrPoints = [];
zoomToPoint('point_1');
function zoomToPoint(data_id) {
// Does array already contain the data?
if (!arrPoints.data_id) {
// Add data to the array
arrPoints.data_id.clientX = somevalue;
arrPoints.data_id.clientY = somevalue;
}
}
This would basically create an array that looks like this:
arrPoints.point_1[]
arrPoints.point_2[]
Where I can access the data in each .point_1 and .point_2.
But I can't create an array based on a variable, like this:
arrPoints.data_id = [];
Because I end up with data_id as the actual name, not the variable that data_id actually is. So how is this usually accomplished? How can I identify each point to the actual array?
Sorry for my lack of basics
Just use an object:
var arrPoints = {};
zoomToPoint('point_1');
function zoomToPoint(data_id) {
// Does array already contain the data?
if (!arrPoints[data_id]) { // square brackets to use `data_id` as index
// Add data to the array
arrPoints[data_id] = {};
arrPoints[data_id].clientX = somevalue;
arrPoints[data_id].clientY = somevalue;
}
}

javascript function returning issue

I want to return the var "source" value for all the element, now when I put the "source" out of each function, it become undefined.I want to return the whole source array. How to do that? any help would be truly appreciated -
function _getSource(){
var product = fpd.getProduct(true);
$(product[0].elements).each(function(i, elem) {
var source = elem.parameters['source'];
})
return source;
alert (source);
}
Assuming that you're actually after an array containing the source property of each element:
function _getSource(){
var product = fpd.getProduct(true);
return $(product[0].elements).map(function(i, elem) {
return elem.parameters['source'];
}).get(); // .get() turns jQuery collection into an array
}
.map is a very good replacement for a .each / push combo. It comes from functional languages where the "map" function just takes an array, transmutes each elements, and returns a new array of those transmuted results.
The final .get is not strictly necessary if you don't mind getting an array-like result back rather than a proper array.
When you write var source you are declaring a new variable scoped to the function of the each callback. Declare it outside and get rid of the var so you are just assigning instead of redeclaring, and you probably also want to build up an array and not just assign. Something like this:
function _getSource(){
var product = fpd.getProduct(true);
var sources = [];
$(product[0].elements).each(function() {
sources.push(elem.parameters['source']);
})
return sources;
}
source is only defined inside the each function because you var'd it there.
Try this instead:
function _getSource() {
return $(fpd.getProduct(true)[0].elements).map(function() {return this.parameters['source'];});
}

Categories