How to dynamically name arrays in javascript? [duplicate] - javascript

This question already has answers here:
dynamic array names javascript
(7 answers)
Closed 7 years ago.
I haven't found an answer to this question on the site. How would I dynamically name arrays in javascript? I need to generate a number of arrays, the number of which is determined at run time. I am trying to make separate ajax requests that sends individual arrays to a php script for processing.
I have come up with this but it does not work:
var 'objectArray'+id = [];

The typical way would be to have an array of arrays.
var arrayOfArrays = [];
arrayOfArrays[id] = []; // add sub array
What you're asking for is a form of dynamic scoping and JavaScript does not support it. You can call the compiler and eval it but that's a pretty bad idea.

Easiest thing is just creating an object and setting them in it
var objectArrays = {};
objectArrays[id] = [];
The way to do literally what you want is finding the scope you're currently in and setting it in it or using eval.

A good way is to use an array of arrays as suggested:
var objectArray = [];
objectArray[id] = [];
If you do not want to use your own array, you can use window object which holds the window global vars in order to store it there as a value as a global var (not a good practice though):
window["objectArray" + id] = [];
Finally, a (bad in this case) alternative way of doing it is by using eval (which is a way to evaluate an expression at runtine in JavaScript in a sense):
eval("var objectArray" + id + " = [];");

Related

Map entries Transitive Operation? [duplicate]

This question already has answers here:
Transforming a Javascript iterable into an array
(8 answers)
Closed 2 years ago.
I want to be able to quickly get the entry set from a map. But the entries function returns an iterator. That's not what I want. Sure, I could write a function to iterate through the entries and build it up into an entry set, but it would be much nicer to have my function say:
return map.entries();
instead of
return buildEntriesArray(map);
It doesn't seem like there's a clean way to code around the iterator problem other than wrap it in a bunch of decorated calls for the various inconsistent Iterator/entry set API cruft.
let a = [["foo.com", 32], ["bar.foo.com", 12]];
let m = new Map(a);
// add to map, etc.
let entries = Object.entries(Object.fromEntries(m.entries()));
How can I make it cleaner?
let entries = Array.from(m.entries());

Make a new array with one element of a multidimenional array using JavaScript [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 3 years ago.
I have a JSON object in a JavaScript function:
[{"PMID":31206477,"MemberID":1287,"recID":6352},
{"PMID":31202264,"MemberID":1245,"recID":5974},
{"PMID":31201299,"MemberID":1184,"recID":3012},
{"PMID":31196160,"MemberID":1241,"recID":3833}]
That is saved to an Multi-dimensional Array
Is there a better way that I can make a make a new Array with only the PMID element without looping and building it. I know that this question is close to a duplicate but I'm not interested in a merge or a concat. Currently I'm doing
var newArray = [];
for (var i = 0; i < this.pmidList.length; i++) {
newArray.push(this.pmidList[i]["PMID"]);
}
This question maybe a duplicate but if the average person can't find it based upon the title then it should not be considered a duplicate. The solution is the same but the question titles are much different.
You can use the Array.map function.
const input = [{"PMID":31206477,"MemberID":1287,"recID":6352},
{"PMID":31202264,"MemberID":1245,"recID":5974},
{"PMID":31201299,"MemberID":1184,"recID":3012},
{"PMID":31196160,"MemberID":1241,"recID":3833}];
const output = input.map(item => item.PMID);
Documentation

What is the most efficient way to find an element in an array? [duplicate]

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 7 years ago.
I get an array of objects from the backend as this one, currently only three elements but in the future will be more.
[{"code":"lng.dropdown.home","text":"Inicio"},
{"code":"lng.dropdown.shop","text":"Tienda"},
{"code":"lng.button.support","text":"Soporte"}]
What is the most efficient way in javascript to find an element in this array by code, and return the text associated? Can we use lambdas expresions here?
you can use array filter to find the nested object(s) that matches your code property:
var arr =
[{"code":"lng.dropdown.home","text":"Inicio"},
{"code":"lng.dropdown.shop","text":"Tienda"},
{"code":"lng.button.support","text":"Soporte"}];
var res = arr.filter(function(x){
return x.code == 'lng.dropdown.home'
})
console.log(res[0])
[].filter returns an array with the objects that return true inside the callback.
As far as efficiency is concerned for loop are proved to be faster but using higher order methods you earn abstraction .
When not using other libraries, I usually map then find the indexOf, as follows:
data[data.map(function(a){ return a.code }).indexOf("code I am trying to find")];
This returns the element of data at the index where code matches the code you're trying to find.
When I have lodash as a dependency, I usually just do this however:
_.find(data, {code:"code I am trying to find"})
(I think that's the proper syntax)
Edit:
Didn't realize you were already using JQuery, the answer using $.grep is probably best.

i value not iterating in Callback functions [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 8 years ago.
This may be a question without any R&D but I am on a busy schedule and very new to these callback functions, The problem is I am getting a json payload from a webapp and I am trying to parse it , so this payload has a array of objects , but when i use this in my script i am getting only the last array index value.
below is the code and attached console output for reference , please suggest where i am going wrong
var case1 = payload.Case;
var i=0;
for(i=0;i<case1.length;i++)
{
var c1 = case1[i];
c1.retrieveAttributes(function(){
console.log(i+ " i");
console.dir(c1.attributes);
});
}
The i value in console is always 6.
You're having an issue with 'closure' scope. Try passing 'i' into your function like this.
var case1 = payload.Case;
var i=0;
for(i=0;i<case1.length;i++)
{
var c1 = case1[i];
c1.retrieveAttributes(function(i){
console.log(i+ " i");
console.dir(c1.attributes);
});
}
That should preserve the true value of 'i'.

How to remove elements from Array? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to empty an array in JavaScript
How to remove all items from jQuery array?
I have array var myArray = [];, I want to clear all items in this array on every post back.
Simplest thing to do is just
myArray = [];
again.
edit — as pointed out in the comments, and in answers to other questions, another "simplest thing" is
myArray.length = 0;
and that has the advantage of retaining the same array object.
you can remove all item in myArray using array length, it's common pattern.
try this
var myArray = [1, 2, 3];
myArray.length = 0; // remove all item
To clear the array values you can do a simple:
myarray = [];
P.s.
jQuery != javascript
There is no such thing as a jQuery array, that's just a javascript array. When a page posts back, it re-renders and all of the javascript is re-run, you don't need to clear the contents of the array.
if, during execution of the page, you wanted to clear a javascript array, just re-initialize it as a new, blank array:
myArray = []; // no var, we are just initializing not declaring

Categories

Resources