I have a function that has a menu param
removeChildCheck:function(menu){
let removeArrayValues = [];
for(var i=0; i < this.checkbox.menu.length; i++){
removeArrayValues.push(this.checkbox.menu[i].value);
}
this.user.permissions = this.user.permissions.filter((i) => !removeArrayValues.includes(i));
},
when I used it like this removeChildCheck('dashboard') im getting length of undefined.
How can I append the param and loop on it? TIA
Do you mean to do:
this.checkbox[menu]
That is, access the property of checkbox that has the name stored in the variable menu? Keep in mind that:
this.checkbox.dashboard
is equivalent to
this.checkbox['dashboard']
and
menu = 'dashboard'
this.checkbox[menu]
As audiodude says, use array syntax: this.checkbox[menu].length
removeChildCheck:function(menu){
let removeArrayValues = [];
for(var i=0; i < this.checkbox[menu].length; i++){
removeArrayValues.push(this.checkbox[menu][i].value);
}
this.user.permissions = this.user.permissions.filter((i) => !removeArrayValues.includes(i));
},
Related
A json response has an array of objects that I want to iterate without having to use the full (I don't know what you would call "results.data.messages.items") long name:
for (var i = 0; i < results.data.messages.items.length; i++) {
console.log( results.data.messages.items[i].id );
}
I know how to iterate over items, but I can't find any way to shorten that down so I don't have to type results.data.messages.items[i].property_name each time and instead could just do item[i].property_name.
I don't want to duplicate the array just for the purpose of having a shorter name.
Assigning the array to a new variable does not duplicate the array—it still refers to the same object. The new variable works sort of like an "alias". Therefore, this is absolutely fine:
var element = results.data.messages.items[i];
Alternatively, you could declare a new variable outside the loop:
var items = results.data.messages.items;
Why don't you shorten it to the element at the specific index, instead of the array:
for (var i = 0; i < results.data.messages.items.length; i++) {
var item = results.data.messages.items[i];
console.log(item.id);
}
EDIT
To keep it simpler, you could iterate through it using the array protoype method forEach, that already assigns each element with any name as you wish:
results.data.messages.items.forEach(function(item) {
console.log(item.id);
});
You could always define these in the for loop's definition
for (var i = 0, items = results.data.messages.items; i < items.length; i++) {
console.log( items[i].id );
}
There is also the usually avoided with
with( results.data.messages ){
for (var i = 0; i < items.length; i++){
console.log( items[i].id );
}
}
Assign it to a separate variable before your loop:
var items = results.data.messages.items;
for (var i = 0; i < items.length; i++) {
console.log( items[i].id );
}
This does not create a new array. Just a new variable that references the same array.
Another option would be to use array's builtin methods to reduce duplication:
results.data.messages.items.forEach(function (item) {
console.log(item.id);
});
I have a listview div on screen and I have added itemDataSource to it successfully
var lettersList = new WinJS.Binding.List(jsonArrayForClearance);
var list_ = document.getElementById("prodListView").winControl;
list_.itemDataSource = lettersList.dataSource;
list_.itemTemplate = document.getElementById("tileTemplate");
list_.forceLayout();
Now in each item I have added a custom input type for user to specify(using template). I want to iterate through all the items of list and obtain the value of that input type in an array.
how can I do it?
EDIT: My question is to access custom input type declared in list items. As such we use following code to access any input type named "inpT"
document.getElementById('inpT');
but how to access the same from list item? can I use Following code(as suggested by user2608614)
var listView = document.getElementById("prodListView").winControl;
var list = listView.itemDataSource.list;
for (var i = 0; i < list.length; i++) {
var item = list.getAt(i);
item.getElementById('inpT');
}
You can iterate through the list elements like this:
var listView = document.getElementById("prodListView").winControl;
listView.itemDataSource.getCount()
.done(function(count) {
for (var i = 0; i < count ; i++) {
listView.itemDataSource.itemFromIndex(i)
.done(function (item) {
//***item will contain your property
});
}
});
Is not the best solution as it make it difficult to chain the promises, I'm also looking for a better one. But it works.
Since you're using a Binding.List you can just iterate through that much like an array.
var listView = document.getElementById("prodListView").winControl;
var list = listView.itemDataSource.list;
for (var i = 0; i < list.length; i++) {
var item = list.getAt(i);
// do something with this item
}
The only thing to remember is that it doesn't support [] and instead you have to use .getAt() and .setAt().
I have a webpage that contains ASP.NET panels and JavaScript that gets all of the components in the page:
var items = Sys.Application.getComponents();
I need to get the name/ID of each of the elements in the items variable. I have tried the following code: (but it doesn't work)
for (var item in items)
{
alert(item.name);
}
What attribute of 'item' contains the name/ID? How can I modify the above code to do this?
Use the get_name() and get_id() functions instead.
var items = Sys.Application.getComponents() ;
for( var i = 0 ; i < items.length; i++ ) {
var item = items[i];
var id = item.get_id();
var name = item.get_name();
}
http://ajax.asp.net/docs/ClientReference/Sys/ApplicationClass/SysApplicationGetComponentsMethod.aspx
None. item is the key/property so you want items[item].name.
However, if items is an array, using for..in to iterate over it is completely inappropriate. In this case use for(var i = 0; i < items.length; i++) and var item = items[i] inside the loop body.
I am stuck here. How can I clean this array:
{"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]}
So that it looks like:
["5201521d42","52049e2591","52951699w4"]
I am using Javascript.
You just need to iterate over the existing data array and pull out each id value and put it into a new "clean" array like this:
var raw = {"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var clean = [];
for (var i = 0, len = raw.data.length; i < len; i++) {
clean.push(raw.data[i].id);
}
Overwriting the same object
var o = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
for (var i = o.data.length; i--; ){
o.data[i] = o.data[i].id;
}
What you're doing is replacing the existing object with the value of its id property.
If you can use ES5 and performance is not critical, i would recommend this:
Edit:
Looking at this jsperf testcase, map vs manual for is about 7-10 times slower, which actually isn't that much considering that this is already in the area of millions of operations per second. So under the paradigma of avoiding prematurely optimizations, this is a lot cleaner and the way forward.
var dump = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var ids = dump.data.map(function (v) { return v.id; });
Otherwise:
var data = dump.data;
var ids = [];
for (var i = 0; i < data.length; i++) {
ids.push(data[i].id);
}
Do something like:
var cleanedArray = [];
for(var i=0; i<data.length; i++) {
cleanedArray.push(data[i].id);
}
data = cleanedArray;
Take a look at this fiddle. I think this is what you're looking for
oldObj={"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
oldObj = oldObj.data;
myArray = [];
for (var key in oldObj) {
var obj = oldObj[key];
for (var prop in obj) {
myArray.push(obj[prop]);
}
}
console.log(myArray)
Use Array.prototype.map there is fallback code defined in this documentation page that will define the function if your user's browser is missing it.
var data = {"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var clean_array = [];
for( var i in data.data )
{
for( var j in data.data[i] )
{
clean_array.push( data.data[i][j] )
}
}
console.log( clean_array );
You are actually reducing dimension. or you may say you are extracting a single dimension from the qube. you may even say selecting a column from an array of objects. But the term clean doesn't match with your problem.
var list = [];
var raw = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
for(var i=0; i < raw.data.length ; ++i){
list.push(raw.data[i].id);
}
Use the map function on your Array:
data.map(function(item) { return item.id; });
This will return:
["5201521d42", "52049e2591", "52951699w4"]
What is map? It's a method that creates a new array using the results of the provided function. Read all about it: map - MDN Docs
The simplest way to clean any ARRAY in javascript
its using a loop for over the data or manually, like this:
let data = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},
{"id":"52951699w4"}]};
let n = [data.data[0].id,data.data[1].id, data.data[2].id];
console.log(n)
output:
(3) ["5201521d42", "52049e2591", "52951699w4"]
Easy and a clean way to do this.
oldArr = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]}
oldArr = oldArr["data"].map(element => element.id)
Output: ['5201521d42', '52049e2591', '52951699w4']
I have an array of strings in Javascript like `var elements = ["string1", "string2"]; The array is created dynamically so it could contain any number of strings. I want to associate a counter to each element of the array. The counter will increment or decrement during the webpage's life.
I was going to try element["string1"].counter = 1; but it didn't work.
What's a good way to implement this?
If you had an array var elements = ["string1", "string2"], you could not access an element with elements["string1"], you are using the value not the index. elements[0] is the correct form of access to the element, using the numerical key.
Even then, strings are special types of object and do not appear to take additional parameters readily, at least not when I tested a moment ago. Which is odd.
You could quickly knock the array in to a set of objects with separate text and counter components.
var elements = ["string1", "string2"];
var elementsWithCounter = [];
for(var index = 0; index < elements.length; index++) {
elementsWithCounter[i] = { text: elements[index], counter: 1 };
}
You could also create a "hash table" using a plain object such as:
var counter = {};
for(var i = elements.length; i--; ) {
counter[elements[i]] = 1;
}
Then you could increment the counter with:
counter['string1'] += 1;
or
counter[elements[0]] += 1;
This might help you.
elementArray = ["string1", "string2"]
function setCounter(str, val) {
for (var i = 0; i < elementArray.length; i++) {
if (str === elementArray[i]) elementArray[i].counter = val;
}
}
function getCounter(str) {
for (var i = 0; i < elementArray.length; i++) {
if (str === elementArray[i]) return elementArray[i].counter;
}
}
setCounter("string1", 5);
getCounter("string1");
Alternatively just access elementArray[index].counter
Javascript primitives/built in objects can't have properties/attributes added to their prototype (i.e. String.prototype.counter = -1 doesn't work correctly). Image, String, Date, Array all can't have properties added.
Maybe instead of a string you should make it an object, similar to what Orbling has posted.