Create array names dynamically based on string values in Array Javascript [duplicate] - javascript

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 7 years ago.
var sub=["Maths","Chemistry","Physics"];
for(var i=0;i<sub.length;i++)
{
var sub[i]=[]; // this line has error
}
I want to create and get result as below:
Maths[],Chemistry[],Physics[]
If it is not possible to get in this way is there any alternate in Javascript to achieve the same

var sub=["Maths","Chemistry","Physics"];
var result = {};
for(var i=0;i<sub.length;i++)
{
result[sub[i]] = [];
}
I also recommend you read this article which has a good explanation on how to use objects as associative arrays.

Hopefully this example helps in addition to the above responses. You can past this code in a browser console and play around with it.
var dict = {Math:[], Physics:[], Chemistry:[]};
dict["Math"] = [0, 1, 2];
dict["Chemistry"] = ["organics", "biochemistry"];
dict["Physics"] = ["kinematics", "vectors"];
/*retrieve code by typing following one by one*/
dict["Math"]
dict["Chemistry"]
dict["Physics"]

Related

How to make an array by one string in JS [duplicate]

This question already has answers here:
How do I split a string, breaking at a particular character?
(17 answers)
Closed 2 years ago.
I get one string by query like '5e6,5e4,123'.
And I want to make an array containing this query as below in JS.
['5e6', '5e4', '123']
How can I make this? Thank you so much for reading it.
You can use .split(',')
var str = "5e6,5e4,123";
var array = str.split(',');
console.log(array);
You can read more on this here
Use String.split:
console.log('5e6,5e4,123'.split(","))
var query = '5e6,5e4,123';
var queries = query.split(‘,’);
You can make use of split method of string like below:
var res = str.split(',');
const output = input.split(',');

Query syntax for JSON lookup data with var ( not condition ) [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 6 years ago.
I'm trying to filter some JSON data, but I would like the lookup to be based on selection of a drop down. However, I just can't get the syntax correct when trying to do this. Currently the following works in my code, great:
var as = $(json).filter(function (i, n) {
return (n.FIELD1 === "Yes"
});
However, what I would like to do is replace the FIELD1 value with a var from the drop down. Something like this following, which is not working:
var dropdownResult = "FIELD1";
var as = $(json).filter(function(i, n) {
return (n.dropdownResult === "Yes"
});
I'm trying to get the var to become the field name after the n. but it's not working.
Thanks for your time. Sorry if this has been answered many times before and is obvious to you.
To use a variable value as the key of an object you should use bracket notation, like this:
var dropdownResult = "FIELD1";
var as = $(json).filter(function(i, n) {
return n[dropdownResult] === "Yes";
});
I removed the extraneous ( you left in your code - I presume this was just a typo as it would have created a syntax error and stopped your code from working at all.
Also note that it's much better practice to use a boolean value over a string 'Yes'/'No'

Appending an item to an array with a variable key [duplicate]

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 7 years ago.
I am trying to append to a Javascript array in a loop.
I am writing this:
var total_val = (unemployment_multi + laws_multi + family_multi + mobility_multi) / 5;
country_vals.push({total_val:key});
But I end up having a bunch of objects with total_val as the key, rather than the value of total_val.
How do I create an array key with the value that is in total_val? Would I do something like country_vals.total_val.key or something?
EDIT: My goal is to have all of the values in total_val sortable by number - it is going to be a number from 1-10, and I want to sort in order of lowest to highest or highest to low (doesn't matter which), and each will have at least one of the key variable attached to it, but possibly more than one.
You need to use the bracket notation to create an object with dynamic keys
var total_val = (unemployment_multi + laws_multi + family_multi + mobility_multi) / 5;
var obj = {};
obj[total_val] = key;
country_vals.push(obj);
Try this:
country_vals[total_val] = key
Or:
total_val = ''+total_val
country_vals.push({total_val:key});

what is the best way to fetch property list from json array [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 7 years ago.
I want to fetch a property list from a json array.
below is json array
[
{
treeName: 'tree_A',
prefix: 'prefix'
},
{
treeName: 'tree_b',
prefix: 'prefix1/'
}
]
After running code, my expectation result is ["tree_A","tree_B"];
Below is my implementation:
var treeNames = [];
for (var index = 0; index < config.treeSources.length; index++) {
treeNames.push(config.treeSources[index].treeName);
}
I want to find a best implementation to make code beautiful..
any one want to play it?
Check out Lodash/Underscore's _.pluck function. It does exactly what you want:
var treeNames = _.pluck(config.treeSources, 'treeName')
Using an entire utility library like Lodash or Underscore is probably overkill if your only going to use it for this one function, however, although they do provide a wide variety of very useful other functions.
I'll do it something like bellow using native map
var data = [ { treeName: 'tree_A', prefix: 'prefix' }, { treeName: 'tree_b', prefix: 'prefix1/' } ];
var treeNames = data.map(function (tree) {
return tree.treeName;
});
console.log(treeNames);
Note:- The IE8 doesn't support map function, so if want this on IE8 you have to use native for loop or some library like underscorejs.

Getting the first item in an [word, word] [duplicate]

This question already has answers here:
How to get the first element of an array?
(35 answers)
Closed 8 years ago.
I am trying to get the first word out of the variable var solution = [cow, pig]
I have tried everything from strings to arrays and I can't get it. Please help.
As per the comments
solution[0]
Will return the first item in the array.
solution[1]
would be the second, or undefined if the array was:
var solution = [cow]
Is solution an array, or is it in that form? (var solution = [cow, pig]) You also need to add quotes around those values, unless those values are defined variables.
You need to change the variable to look like this:
var solution = ['cow', 'pig']
If so, just get the value at subscript 0.
var result = solution[0];
console.log(result);
If you mean an string like
solution = "cow pig".
Do
solution = solution.split(' ')[0];
console.log(solution); //Will return cow

Categories