Hello i have selectbox to show from javascript array.
<h6><strong>Brand</strong></h6>
<select data-placeholder="Brand..." multiple id="brand" style="width:200px;height:50px;margin: 0;">
<script language="javascript">print_brand1("brand");</script>
</select>
But when i choose one of selectbox data then it get values. Here is javascript code
var brand_arr = new Array(
1:"Acer",
2:"Dell"
);
function print_brand1(brand_id){
var option_str = document.getElementById(brand_id);
option_str.length=0;
option_str.selectedIndex = 0;
for (var i=0; i<brand_arr.length; i++) {
option_str.options[option_str.length] = new Option(brand_arr[i],brand_arr[i]);
}
}
How do i get keys (not values) when i choose one of selectbox data?
Your code will not work in its current state, however if you insist on keeping your current array structure you would need:
var brand_arr = {
1: "Acer",
2: "Dell"
};
Which syntactically makes little sense, assigning a key of 1/2 makes little sense when you could just get this number by using the current index + 1.
Note that with the changes above, in order to assign the keys 1 and 2 we are having to iterate over a Javascript Object and not a Javascript Array.
If you wanted to print 1 and 2 you could then do:
for(var k in brand_arr) {
if(brand_arr.hasOwnProperty(k)) {
console.log(k); // key
console.log(brand_arr[k]); // value
}
}
Although this answers your problem, I would still consider the structure of your data, it would make much more sense to have something like:
var brand_arr = [
{ brand: 'Acer', price: 200 },
{ brand: 'Dell', price: 200 }
];
Note how in the above example we can add extra details about that brand in the JSON. We could then iterate over the brand array to get more detail about each brand in a much more readable format opposed to a user assigned index and its name.
Related
I've got an ordered array of objects, myBros. I want each one to get its own index in the array (which I'm storing as myPlace) and store the ID of the following one, with the last object storing the ID of the first.
The code below results in each object storing the ID of the last object, not the next one. On a positive note, the last object stores the ID of the first one.
EDIT: Sorry, I should have been more specific-this function lives in an object (a React component) which has some props, one of which is an id. getNextBroId returns a value based on the component's index.
What am I doing wrong?
EDIT: reworked the code in accordance with Daniel Beck's suggestion, still having the same problem.
for (let i = 0; i < myBros.length - 1; i++) {
myBros[i].nextBroId = myBros[i + 1]._id;
}
myBros[myBros.length - 1].nextBroId = myBros[0]._id;
const myPlace = myBros.findIndex(p => p._id === id);
const getNextBroId = () => {
return myBros[myPlace].nextBroId;
};
EDIT: I've posted the entire component here: React-cycling through components in an array and am considering closing this question to avoid redundancy.
This is one of those cases where boring old iteration is going to be a lot easier (and more performant) than the more exciting new techniques.
var myBros = [
{_id: "a"},
{_id: "b"},
{_id: "c"},
{_id: "d"},
{_id: "e"}
]
// step through all but last element in the array, link each one to the next
for (var i = 0; i < myBros.length - 1; i++) {
myBros[i].nextBroId = myBros[i + 1]._id;
}
// link the last one back to the first
myBros[myBros.length - 1].nextBroId = myBros[0]._id;
// and we're done
console.log(myBros);
(I'm not entirely sure why you would want to turn an array into a pseudo linked list, but I assume you have your reasons...)
I'm working with a large dataset that needs to be efficient with its Mongo queries. The application uses the Ford-Fulkerson algorithm to calculate recommendations and runs in polynomial time, so efficiency is extremely important. The syntax is ES6, but everything is basically the same.
This is an approximation of the data I'm working with. An array of items and one item being matched up against the other items:
let items = ["pen", "marker", "crayon", "pencil"];
let match = "sharpie";
Eventually, we will iterate over match and increase the weight of the pairing by 1. So, after going through the function, my ideal data looks like this:
{
sharpie: {
pen: 1,
marker: 1,
crayon: 1,
pencil: 1
}
}
To further elaborate, the value next to each key is the weight of that relationship, which is to say, the number of times those items have been paired together. What I would like to have happen is something like this:
// For each in the items array, check to see if the pairing already
// exists. If it does, increment. If it does not, create it.
_.each(items, function(item, i) {
Database.upsert({ match: { $exist: true }}, { match: { $inc: { item: 1 } } });
})
The problem, of course, is that Mongo does not allow bracket notation, nor does it allow for variable names as keys (match). The other problem, as I've learned, is that Mongo also has problems with deeply nested $inc operators ('The dollar ($) prefixed field \'$inc\' in \'3LhmpJMe9Es6r5HLs.$inc\' is not valid for storage.' }).
Is there anything I can do to make this in as few queries as possible? I'm open to suggestions.
EDIT
I attempted to create objects to pass into the Mongo query:
_.each(items, function(item, i) {
let selector = {};
selector[match] = {};
selector[match][item] = {};
let modifier = {};
modifier[match] = {};
modifier[match]["$inc"] = {};
modifier[match]["$inc"][item] = 1
Database.upsert(selector, modifier);
Unfortunately, it still doesn't work. The $inc breaks the query and it won't let me go more than 1 level deep to change anything.
Solution
This is the function I ended up implementing. It works like a charm! Thanks Matt.
_.each(items, function(item, i) {
let incMod = {$inc:{}};
let matchMod = {$inc:{}};
matchMod.$inc[match] = 1;
incMod.$inc[item] = 1;
Database.upsert({node: item}, matchMod);
Database.upsert({node: match}, incMod);
});
I think the trouble comes from your ER model. a sharpie isn't a standalone entity, a sharpie is an item. The relationship between 1 item and other items is such that 1 item has many items (1:M recursive) and each item-pairing has a weight.
Fully normalized, you'd have an items table & a weights table. The items table would have the items. The weights table would have something like item1, item2, weight (in doing so, you can have asymmetrical weighting, e.g. sharpie:pencil = 1, pencil:sharpie = .5, which is useful when calculating pushback in the FFA, but I don't think that applies in your case.
Great, now let's mongotize it.
When we say 1 item has many items, that "many" is probably not going to exceed a few thousand (think 16MB document cap). That means it's actually 1-to-few, which means we can nest the data, either using subdocs or fields.
So, let's check out that schema!
doc =
{
_id: "sharpie",
crayon: 1,
pencil: 1
}
What do we see? sharpie isn't a key, it's a value. This makes everything easy. We leave the items as fields. The reason we don't use an array of objects is because this is faster & cleaner (no need to iterate over the array to find the matching _id).
var match = "sharpie";
var items = ["pen", "marker", "crayon", "pencil"];
var incMod = {$inc:{}};
var matchMod = {$inc:{}};
matchMod.$inc[match] = 1;
for (var i = 0; i < items.length; i++) {
Collection.upsert({_id: items[i]}, matchMod);
incMod.$inc[items[i]] = 1;
}
Collection.upsert({_id: match}, incMod);
That's the easy part. The hard part is figuring out why you want to use an FFA for a suggestion engine :-P.
This is my first time on here, so forgive me if the answer to this is obvious - but can't find a possible solution anywhere.
I'm trying to pull numbers out of a survey I want to set up, which will generate a list of cities. Thus:
var cities = array ['city1', 'city2', 'city3', 'city2', 'city4', 'city1', city2'];
Will generate a list: city1: 2, city2: 3, city3: 1, city4: 1
Is there a way to go through an array like this in Javascript? The cities will not be pre-determined - ie people could be entering anything.
Thanks in advance for any help you can give me.
tim
Like Niet already answered:
You go through the list and put the keys into a object and increment the values.
var generatedList = {};
for(var i=0;i<cities.length;i++){
if(generatedList[cities[i]]){
generatedList[cities[i]]++;
}else{
generatedList[cities[i]] = 1;
}
}
The answer is "obvious"... if you know where to start. So here's the starting line:
Create an object (literal, {})
Iterate through the array. For each item:
If the item doesn't exist as a key of the object, create the key with value 0
Increment the key on the object by 1
And... done! That's all there is to it.
This has been answered since I started this demo but this should help you understand what's happening. Open this demo with the developer console open to view the output:
http://jsfiddle.net/46wnj/
var cities = new Array('city1', 'city2', 'city3', 'city2', 'city4', 'city1', 'city2');
var citiesObject = {};
for (var x = 0; x < cities.length; x++)
{
if (citiesObject[cities[x]])
{
citiesObject[cities[x]]++
}
else
{
citiesObject[cities[x]] = 1;
}
}
var Animals = {
"Europe": { "weasel.jpg": "squeak", "cow.jpg": "moo"},
"Africa": { "lion.jpg": "roar", "gazelle.jpg": "bark"},
};
function region(a){
var b = "Animals."+a;
for(var index in b) {
var target = document.getElementById('div1');
var newnode = document.createElement('img');
newnode.src = index;
target.appendChild(newnode)
}
}
RELEVANT HTML
<li onclick="europe('Europe')">Europe</li>
Goal: on the click of the Europe <li>, pass the word Europe into my region function where it is then concatenated to produce Animals.Europe
This is in order to identify an array within the object structure at the top using the for(var index in Animals.Europe) loop. Why is the concatenation which produces Animals.Europe not treated in the same way as if I had typed this out?
In addition, you can see that I have used arrays to store an image source and description for different animals. Using my limited coding knowledge this was all I could think of. Is there an easier way to store image/description data in order to produce in HTML?
"Animals." + a is just a string value, e.g. "Animals.Europe", which is not the same thing as Animals.Europe. If you change the first line to var b = Animals[a];, you should be all set.
Edit: and as elclanrs pointed out, it should be region('Europe'), not europe('Europe').
Why is the concatenation which produces Animals.Europe not treated in the same way as if i had typed this out?
In this case the variable b is just a string ("Animals.Europe"), which is treated like any other string (i.e. a list of characters). This means that when you attempt to loop through it (for(index in b)) you will be looping over a simple list of characters.
What you can do instead is use the square brace notation of accessing an objects properties. This means you can instead write var b = Animals[a], retrieving attribute a from Animals. You can read more about working with objects in this way on this MDN page
You can access the europe property using the following
Animals[a]
Also you're calling a "europe" function when you should be calling "region"
You're not storing animals in arrays here, but in objects with the image names as keys. Usually you'll want to use relevant names as keys. For example if you want arrays of animals for each continent
var Animals = {
"Europe": [{
imageSrc: "weasel.jpg",
cry: "squeak"
},{
imageSrc: "cow.jpg",
cry: "moo"
}],
"Africa": [{
imageSrc: "lion.jpg",
cry: "roar"
},{
imageSrc: "gazelle.jpg",
cry: "bark"
}]
};
Now Animals['Europe'] gives an array of objects, where you could eventually store other properties. So if b is an array your loop will now look like:
var b = Animals['Europe'];
for(var i=0; i < b.length; i++) {
var target = document.getElementById('div1');
var newnode = document.createElement('img');
var animalData = b[i]; // The array item is now an object
newnode.src = animalData.imageSrc;
target.appendChild(newnode)
}
Description and Goal:
Essentially data is constantly generated every 2 minutes into JSON data. What I need to do is retrieve the information from the supplied JSON data. The data will changed constantly. Once the information is parsed it needs to be captured into variables that can be used in other functions.
What I am stuck in is trying to figure out how to create a function with a loop that reassigns all of the data to stored variables that can later be used in functions.
Example information:
var json = {"data":
{"shop":[
{
"carID":"7",
"Garage":"7",
"Mechanic":"Michael Jamison",
"notificationsType":"repair",
"notificationsDesc":"Blown Head gasket and two rail mounts",
"notificationsDate":07/22/2011,
"notificationsTime":"00:02:18"
},
{
"CarID":"8",
"Garage":"7",
"Mechanic":"Tom Bennett",
"notificationsType":"event",
"notifications":"blown engine, 2 tires, and safety inspection",
"notificationsDate":"16 April 2008",
"notificationsTime":"08:26:24"
}
]
}};
function GetInformationToReassign(){
var i;
for(i=0; i<json.data.shop.length; i++)
{
//Then the data is looped, stored into multi-dimensional arrays that can be indexed.
}
}
So the ending result needs to be like this:
shop[0]={7,7,"Michael Jamison",repair,"Blown Head gasket and two rail mounts", 07/22/2011,00:02:18 }
shop[1]={}
You can loop through your JSON string using the following code,
var JSONstring=[{"key1":"value1","key2":"value2"},{"key3":"value3"}];
for(var i=0;i<JSONstring.length;i++){
var obj = JSONstring[i];
for(var key in obj){
var attrName = key;
var attrValue = obj[key];
//based on the result create as you need
}
}
Hope this helps...
It sounds to me like you want to extract the data in the "shop" property of the JSON object so that you can easily reference all of the shop's items. Here is an example:
var json =
{
"data":
{"shop":
[
{"itemName":"car", "price":30000},
{"itemName":"wheel", "price":500}
]
}
},
inventory = [];
// Map the shop's inventory to our inventory array.
for (var i = 0, j = json.data.shop.length; i < j; i += 1) {
inventory[i] = json.data.shop[i];
}
// Example of using our inventory array
console.log( inventory[0].itemName + " has a price of $" + inventory[0].price);
Well, your output example is not possible. You have what is a list of things, but you're using object syntax.
What would instead make sense if you really want those items in a list format instead of key-value pairs would be this:
shop[0]=[7,7,"Michael Jamison",repair,"Blown Head gasket and two rail mounts", 07/22/2011,00:02:18]
For looping through properties in an object you can use something like this:
var properties = Array();
for (var propertyName in theObject) {
// Check if it’s NOT a function
if (!(theObject[propertyName] instanceof Function)) {
properties.push(propertyName);
}
}
Honestly though, I'm not really sure why you'd want to put it in a different format. The json data already is about as good as it gets, you can do shop[0]["carID"] to get the data in that field.