Dynamic key names [duplicate] - javascript

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.

Related

JavaScript Undefined when alert(array.length) is called [duplicate]

This question already has answers here:
Length of a JavaScript object
(43 answers)
Closed 2 years ago.
Lately I have been trying to create a webpage with a search feature. My way of implementing this, while not the fastest or most elegant, should work in theory. All it does is split the search term into a list, the delimiter being a space, and then splits the keywords (in dictionary format, with the value being a download link, and with the key being the "keywords" I was referring to) and finally, it has an outer loop looping through the keys (being split each iteration into a list), and an inner loop looping through the words input through the input field. If a word in the search field matches one keyword of the key words list, then that key from the dictionary gets a score of +1.
This should sort the keys into order of best result to worst, and then the code can continue on to process all this information and display links to the downloadable files (the point of the webpage is to supply downloads to old software [of which I have collected over the years] etc.). However, when I run the program, whenever the alert(ranking.length) function is called, all I get is undefined in the output window.
Here is the code. (The search() function is called whenever the search button is pressed):
var kw_href = {
"windows":["windows3.1.7z"],
"ms dos 6.22":["ms-dos 6.22.7z"]
}
function search(){
var element = document.getElementById("search_area");
var search_term = element.value.toLowerCase();
var s_tags = search_term.split(" ");
var keys = Object.keys(kw_href);
ranking = {
"windows":0,
"ms dos 6.22":0
};
for (i = 0; i < keys.length; i++){
keywords_arr = keys[i].split(" ");
for (x = 0; x < s_tags.length; x++){
if (keywords_arr.includes(s_tags[x])){
ranking[keys[i]] = ranking[keys[i]] + 1;
}
}
}
// now we have a results list with the best results. Lets sort them into order.
alert(ranking.length);
}
Edit
alert(ranking.length) line is for debugging purposes only, and I was not specifically trying to find the length.
ranking is a generic object, not an array, so it won't have a computed length property.
If you want to count the number of properties in it, convert it to an array with Object.keys(ranking).
ranking should be array of object like ranking =[{"windows":0,"ms dos 6.22":0},{"windows":1,"ms dos 6.22":10}]
Then length ranking.length will work

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});

how to use Javascript "document.getelementbyid" [duplicate]

This question already has answers here:
Why won't my inputs value sum?
(5 answers)
Closed 8 years ago.
i am trying to make a maths engine with JavaScript and HTML.
Here is (http://i.stack.imgur.com/NCEa4.jpg)
The alert from the js alert() function works but the output from it is wrong:
'HTMLObject'
Value of the input field is always a string. So when you use + operator with two strings it concatenates them. If you want to add two numbers you need first to convert strings to numbers. There are multiple ways to do it, for example:
var plus = parseInt(one) + parseInt(two);
Or you can use Number(one), or another unary + operator: +one + +two, but this might look confusing.
Use 'parseInt()' function to convert those values to integers first and then add the values.
make your variable plus like this:
var plus = parseInt(one) + parseInt(two);
You need to enclose your function code in curly braces { & }.
So Use:
function Maths(){
var one=document.getElementById("fid").value;
var two=document.getElementById("sid").value;
var plus=Math.parseInt(one)+Math.parseInt(two);
alert(plus);
}
Also use parseInt() to make data type conversion to convert to int in JavaScript.
Hope it'll help you. Cheers :)!!
Will be better if you use second argument in parseInt for be sure that value will be in decimal system.
function Maths() {
var one = document.getElementById("fid").value,
two = document.getElementById("sid").value,
plus = Math.parseInt(one, 10) + Math.parseInt(two, 10);
alert(plus);
}

How to store integer indexed data in Javascript?

I'm coming from working in PHP for many years and having trouble wrapping my head around creating some more complicated data structures in JS for objects that are integer IDed. I need to build an object the stores these simpler objects hierarchically keyed on their integer ids. So if I have the following objectes each of which has a unique integer id:
section, element, item, entry
in php I would do something like
$arr[$section_id][$element_id][$item_id][$entry_id] = $entry;
In javascript this does not work. I know I could technically wrap those IDs in quotes to force it but that seems like a bad idea. Similarly I could create an object and use the quoted integer approach but again that seems hacky.
Right now I am storing the data in regular integer indexed arrays and then using caolan's async detect to look up a particular member by ID. This works but seems extremely messy compared to the php equivalent. I'm hoping there's a cleaner way to do this in JS.
TIA!
since javascript cannot save an array with string index, i use these :
var namespace = function(name, separator, container){
var ns = name.split(separator || '.')
, o = container || window
, i = 0;
while (i++ < ns.length) o = o[ns[i - 1]] = o[ns[i - 1]] || {};
return o;
}
namespace(arr + '.' + section_id + '.' + element_id + '.' + item_id + '.' + entry_id) = entry;
// ex : namespace('arr.1.3.2.6') will product arr.1.3.2.6 object
This is a little ugly, but it will get you pretty close to what you want.
You can add a method to the JavaScript Array class like so:
Array.prototype.g = function(index) {
if (this[index] == undefined) {
this[index] = [];
}
return this[index];
}
Then, to set something you would do this:
var test = [];
test.g(5).g(7)[5] = 1;
Unfortunately, for the last entry you'd have to remember to use the regular notation to set the value.
You would retrieve it like you expect:
test[5][7][5]; //1
Obviously I just pulled g out of thin air, you could come up with your own function name.
Disclaimer: People tend to frown on extending the built in types using the prototype chain, but as far as I know most major frameworks no longer do this so unless you or some third party JS is using the same name to extend Array somewhere else you should be fine.

Categories