how to add dynamic items in a collection in javascript? - javascript

i want to add number of elements in a collection in javascript,as doing in following vb's code
Dim myList As New List(Of String)
Dim i As Integer
For i = 0 To rep_UnAssignComps.Items.Count
myList.Add(i)
Next
I want to compare this collection with a particular value.provide me syntax for comparing the value also. like
myList.Contains(val1)

Not sure what you want to store in the collection but in java-script, you have two choices to achieve collections.
First is to use arrays. For example,
var arr = []; // empty array
arr.push('A');
arr.push('B');
arr.push('C');
alert(arr.length); // alerts 3
alert(arr[1]); // alerts B (zero based indexing)
To check if any element exists or not, you have to run a loop over an array comparing element at each index.
Another method will be using java-script object as hash table. Essentially, every java-script object can have multiple properties that are essentially name-value pairs. For example,
var o = { } // empty object
o["prop1"] = "A"; // Added property named prop1 with value "A"
o["prop2"] = "B"; // Added property named prop2 with value "B"
o["prop3"] = "C"; // Added property named prop2 with value "C"
alert(o["prop1"]); // alerts A
alert(o.prop2); // alerts B - notice alternate syntax
alert(o["prop4"]); // alerts undefined - because we are accessing non-existent property
if (o["prop3"]) {
alert("prop3 exists"); // to check for some property
}
for (p in o) { // iterate all properties
alert(p); // alerts property name
alert(o[p]); // alerts property value
}

Use push method http://www.w3schools.com/jsref/jsref_push.asp

var myList = []
var i = 0;
if "rep_UnAssignComps" is an array use for loop else use for in
if (rep_UnAssignComps instanceof Array) {
for (i = 0; i < rep_UnAssignComps.length; i++){
myList.push(i);
}
}else {
for(var name in rep_UnAssignComps){
if (rep_UnAssignComps.hasOwnProperty(name)){
myList.push(i);
i++;
}
}
}
To compare use:
//Returns the first index at which a given element can be found in the array, or -1 if it is not present
myList.indexOf(val1);

Related

I have an issue with removing an object key with a for in loop

I'm using a for x in loop to check if a value is == to [] and if so remove the property using remove but it just does not seem to work.
const whosOnline = (a) => {
var obj = { online:[],
offline:[],
away:[] };
for(let i = 0; i < a.length; i++){
if(a[i].lastActivity > 10 && a[i].status == 'online'){obj.away.push(a[i].username)}
else if(a[i].status == 'offline'){obj.offline.push(a[i].username)}
else{obj.online.push(a[i].username)}
}
for(let x in obj){
console.log(obj[x])
if(obj[x] === []){delete obj[x]}}
return obj
}
you were close, however you also need to reference the array index for each object key value. Comments explaining this in the code below.
var obj = { online:[],
offline:[],
away:[] };
for(var x in obj){
if(!obj[x][0]){ // The 0 is the index inside the online array, next loop it will be the offline array and then the away array.
console.log('The array is empty');
// Do what you want to do now that it is empty
// This will continue to loop through and check the value of all the keys in the object.
}
}
console.log('done');
Good luck -
Mitch from
https://spangle.com.au
Using some debugging (simply testing if a console.log gets printed for instance) you find that your if-condition is never true.
This is because you test if an array equals a newly created empty array. This can never be the case, because objects are compared by object reference instead of value.
Instead you want to probably test to see if your array is empty by doing ‘if(obj[x].length===0)’ (or shorter: ‘if(!obj[x].length)’)

chineseFood[array[0]] = array[array.length-1];

I don't understand the purpose of this = sign on the sixth line in the code block below. I understand how the argument grabs each index number of the array, I just don't understand why chineseFood[array[0]] = array[array.length-1]; In other words, I don't get the purpose of the equal sign as if it were almost comparing each other to be stored in the empty object that is stored in the variable chineseFood. Could someone please clarify? It would be much appreciated.
function transformFirstAndLast(array) {
var chineseFood = {};
//takes 1st element (at index 0) and sets it to the last element (nth index): array(length-1)
chineseFood[array[0]] = array[array.length - 1];
return chineseFood;
}
console.log( transformFirstAndLast(['Orange', 'Lemon', 'Pork', 'Chicken']) );
Output Below
{Orange: "Chicken"}
The equals sign is not comparison, it is assignment. chineseFood is an object, which means that it can be treated like a dictionary, and its properties can be accessed using the [] operator instead of the . operator:
myObj = {
foo: "bar"
};
console.log(myObj["foo"]); // bar
console.log(myObj.foo); // bar
Likewise, you can also assign properties this way:
myObj = {};
myObj["foo"] = 3;
console.log(myObj["foo"]); // 3
console.log(myObj.foo); // 3
This is what your code is doing. It is retrieving the value of array[array.length-1], which is "Chicken". Then it is assigning this value to the property of chineseFood that has the name represented by array[0], which happens to be "Orange". Thus, the property named Orange on chineseFood is set to array[array.length - 1], which is why chineseFood evaluates to {Orange: "Chicken"}.
This method of accessing properties is especially useful when you don't know the name of the property you will be changing in advance, as is the case with this code, or when you want to create properties that have names that would otherwise be illegal:
myObj = {
".you can't usually use with spaces or start w/ periods": false
};
myObj[".you can't usually use with spaces or start w/ periods"] = true;
console.log(myObj[".you can't usually use with spaces or start w/ periods"]);
// there is no way to read this property the normal way
Basically what is does is:
your object is :
var obj = {Orange: "Chicken"};
And Your array is :
var arr = ['Orange','Lemon','Pork','Chicken']
What this line says is pick first element of the array and check for this prop in object and change its value to last element of array, here:
arr[0] = "orange";
So this line :
obj[arr[0]] can be seen as obj['orange'].
After that you change its value:
Obj[arr[0]] = arr[arr.length-1] which can be written as obj['orange'] = 'chicken'

How to join Array Values as keys to get jSON object value

I have been working on a function that loops through a JSON object recursively, and want to use each key it finds as the class value of an element to change the .text value of that element in jQuery. So, far so good, however, as I am able to get the Keys recursively as well, I'm struggling on finding a way to input all of those keys to get each json objects values:
function eachRecursive(obj, aKey)
{
aKey = aKey === null ? '' : aKey;
for (var k in obj)
{
if (typeof obj[k] == "object" && obj[k] !== null)
{
aKey += k + '_';
eachRecursive(obj[k], aKey);
}
else
{
if (obj.hasOwnProperty(k))
{
console.log(obj[k]);
if ($('.player_' + aKey + k).length)
{
var props = aKey.split('_');
props.clean("");
$('.player_' + aKey + k).text(obj[k]);
}
}
// might not even need this.
aKey = '';
}
}
}
So, text(obj[k]) isn't going to work here since the json is looping through objects inside objects recursively.
So, aKey is a string that gets used to check if the class exists (should be appending each key of the json object into it. Than should check if exists, if it does exist, should plug in the value into the .text of that element.
But what I'm sruggling here with is how to get the value from all of the keys that get plugged into an array called, props. So I will need to use each value in the array as keys for obj object to get the corresponding json value.
Can someone please help me here?
The .clean prototype added to Array just simply removes any empty values in the array. Specifically the last array index (since it splits on _).
How to pass array values into obj to get the json value?
For Example, if:
var props = ['name', 'first', 'last'];
// How to do this so we can get the value?
obj['name']['first']['last'][k]
Iterate over the props array and lookup the value in turn using bracket notation.
var value = obj;
for (var i = 0; i < props.length; i++) {
value = value[props[i]];
}
value = value[k];

Jquery/javascript creating object

So, I want to create an object (semi-automatically) using Jquery.
Instead of posting all of my code here, I'll give an example of what I want to do:
var myobject = {
'name1': {
'coord1':true,
'coord2':false,
'coord3':false,
},
'name2': {
'coord4':true,
'coord5':false,
'coord6':false,
}
}
1) I first want to check if 'nameX' is already in my object, if so, continue to step 2, if not, I want to add the name, and coordX with value true or false.
2) If 'nameX' is in the array, I want to check i 'coordX' is in the array. If so, I need to check if the corresponding value (true or false) is the same, and if not, replace it. If 'CoordX' is not in the object, I want to add it with the corresponding value.
For example:
var mynewname = 'name3';
var mynewcoord = 'coord5';
var mynewvalue = 'true';
var mynewname2 = 'name1';
var mynewcoord2 = 'coord4';
var mynewvalue = 'false';
When checking these values with the object this should give:
var myobject = {
'name1': {'
coord1':true,
'coord2':false,
'coord3':false,
'coord4':false
},
'name2': {
'coord4':true,
'coord5':false,
'coord6':false
},
'name3':{
'coord5':true
}
}
I hope someone can help me with this. Thank you
In order to find out if an object contains a property with a given name, you have a couple of choices.
You can use the in operator with a string property name:
if ("nameX" in myobject) {
// The object referenced by `myobject` (or its prototype)
// has its own property called "nameX"
}
else {
// It doesn't
}
in will check the object and its prototype. That probably doesn't matter for the simple objects you're using.
Or you can use hasOwnProperty, which only checks the object and not its prototype:
if (myobject.hasOwnProperty("nameX")) {
// The object referenced by `myobject` has its own property called "nameX"
}
else {
// It doesn't
}
So for instance, if you want to see if name1 is in myobject and, if not, add name1 referencing a blank object, you'd do this:
if (!("name1" in myobject)) {
myobject.name1 = {}; // No, add it and give it a blank object as its value
}
And similarly for the coordX properties of the objects you're referencing from myobject.nameX.

Why does the following JavaScript test show the element as not belonging to the array?

The code is very simple and I would be expecting true however it returns false
var markets = ["AB", "CD"];
console.log("AB" in markets);
I think you're meaning if (markets.indexOf('AB') !== -1). in essentially checks if the test is a property of the object, not if an element is contained within the array.
For more information, look at Array.indexOf vs. the in operator.
Because in looks up property names, not values. Your property names are the array indices.
From MDN's page on the in operator:
The in operator returns true if the specified property is in the specified object.
prop A string or numeric expression representing a property name or array index
Note a property name or array index. The in operator does not search for property values, but for property names. In this case, the property names are 0 and 1, so 0 in markets will return true.
You should use indexOf, in browsers that support it, and shim it in those that don't.
Because in is meant for objects, not arrays. If you want to reliably do this you have to search through each element in the array:
for( var i=0, l=markets.length; i<l; i++ ){
if( markets[i] === 'AB' ){
// do something
}
}
The following will work, which is what you're thinking:
var markets = { AB: 1, CD: 1 };
console.log( "AB" in markets );
In only works when you are using an object, not an array. So this will work:
var markets = {
AB: 'AB',
CD: 'CD'
};
'AB' in markets; // true
As said in won't help you in this case.
I guess you'll have to write a searching function.
Here's one:
function inArray(ArrObj, Search){
var exists = false;
for (var i = 0; i < ArrObj.length; i++){
if (ArrObj[i] == Search){
return true;
var exists = true;
break;
}
else if ((i == (ArrObj.length - 1)) && (!exists)){
if (ArrObj[i] != Search){
return false;
}
}
}
}
I think you want something like this, console.log(markets[0]);

Categories

Resources