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});
Related
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'
This question already has answers here:
remove all items in array that start with a particular string
(5 answers)
Closed 7 years ago.
I have this simple array
var array = ['x.89999', 'y.sisisis', 'x.585858'];
I want to remove all the items in the array starting by 'x.' so to return this array:
['y.sisisis']
How can i do this without having to loop or iterate all the entire array? (i know it's probably not possible so don't mind if not possible)
Is there some builtin / native code i can use?
Thanks
you may use array.filter()
var newArray = array.filter(function(item){
return item.indexOf('x.') !== 1;
});
there is no way to do this job without looping through the whole array.
The only case – array is sorted alphabetically. But sorting demands looping through too
Assuming that the items to be removed will always precede the other items alphabetically (ie x is before y), you can sort your array and then break the loop as soon as the non-x value has been found:
function filter(arr) {
arr.sort();
for (var i = 0, l = arr.length; i < l; i++) {
if (arr[i][0] !== 'x') {
break;
}
}
return arr.slice(i);
}
filter(arr); // logs: "Iterated to 5 of array length 9"
DEMO
Of course, as JazzCat mentions, this is no good if you only have one y value and it's right at the end of the array - you're still going to have to iterate over the whole array.
Alternate option is to use regular expression, something like this. Fix your regex according to your requirement.
var array = ['x.89999', 'y.sisisis', 'x.585858'];
var filtArr = array.filter(function(x){
return x.match("^[x].+$");
});
console.log(filtArr);
One different answer not using explicit iteration or Array.prototype.filter:
var array = ['x.89999', 'y.sisisis', 'x.585858'];
array = array.join("#").replace(/(#?x\.\w*)/g,"").replace(/^#/,"").split("#");
//["y.sisisis"]
Of course you will need to take care of the separator character.
The good point is that it works on old browsers (ie8) while Array.prototype.filter does not.
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"]
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
This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 9 years ago.
I am trying to generate object elements dynamically from a loop by passing an integer in the initial i.e common prefix of the elements.
Like this:
if(inventory.inventory_obj.length){
obj.inventory_length = inventory.inventory_obj.length;
for(var x=0; x < inventory.inventory_obj.length; x++){
obj.warehouse_+x = inventory.inventory_obj[x].warehouse;
obj.name_+x = inventory.inventory_obj[x].name;
obj.space_+x = inventory.inventory_obj[x].space;
obj.cost_+x = inventory.inventory_obj[x].cost;
obj.quantity_+x = inventory.inventory_obj[x].quantity;
obj.level_+x = inventory.inventory_obj[x].level;
obj.status_+x = inventory.inventory_obj[x].status;
obj.deleted_+x = inventory.inventory_obj[x].deleted;
}
}
Doing the above I get "Invalid left-hand side in assignment" error
I have tested the inventory.inventory_obj through console.log(inventory.inventory_obj) and verified that it has the needed values.
Other tries I have made include
obj.warehouse_+""+x = inventory.inventory_obj[x].warehouse;
obj.warehouse+"_"+x = inventory.inventory_obj[x].warehouse;
obj.warehouse_+x.toString() = inventory.inventory_obj[x].warehouse;
obj.warehouse.concat("_"+x+"") = inventory.inventory_obj[x].warehouse;
//Eliminating the underscore
obj.warehouse+x = inventory.inventory_obj[x].warehouse;
All the above failed.
Please someone help me understand what I am doing wrong.
To create the property name dynamically, use the square bracket notation:
obj['warehouse_' + x] = nventory.inventory_obj[x].warehouse;
Your can't have + in the name obj.warehouse_+x and all other instances like that.
You need to use: obj["warehouse_" + x] for dynamic object key names.
For concatenation try using:
obj["warehouse_" + x] = obj["warehouse_" + x] + inventory.inventory_obj[x].warehouse;
There is no concatenation operator for objects like there is for strings or numbers (+=).
Although the language won't accept arithmetic names unless you are actually making a string out of it, I think you will have better semantic by using arrays instead of many simlar-named variables.
For example, if there is many indexed obj.warehouse, you should initialize it as an array:
obj.warehouse=[];
Then, to put something into it:
obj.warehouse[x] = inventory.inventory_obj[x].warehouse;
It will be easier for you to access it later because you won't have to concatenate every time you want to access a warehouse. Also, as long as there are "concatenating" accesses, debugging can be a pain whenever something is renamed.