I want to loop through a list of element which have dynamic name's value, like item1,item2 etc. but I got undefined like below.
len = $('.aws').length + 1;
var obj = [],
temp = {};
for (var i = 1; i <= len; i++) {
console.log(i)
temp["index"] = $('.aws[name="item' + i + '"]').val()
obj.push(temp);
}
console.log(obj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" class="aws" name="item1" value="1.jpg">
<input type="hidden" class="aws" name="item2" value="2.jpg">
The problem is that you're pushing a reference to the same object on each iteration. In doing so, the index property on the temp object will be the value from the last iteration.
In addition, there are only two elements, and the for loop was executed three times because of the condition i <= len (it should have been i < len). Due to this, the value was undefined on the last iteration, because the element doesn't exist. This resulted in all the index properties on the temp property being set to undefined.
If you want a native JS solution, you could simply use the following instead:
var elements = document.querySelectorAll('.aws');
var values = [];
for (var i = 0; i < elements.length; i++) {
values.push({index: elements[i].value});
}
In the snippet above, a new object is pushed to the values array on each iteration (rather than a reference to the same object). The for loop condition is also i < elements.length (rather than i <= elements.length), so it will only iterate 2 times (rather than 3 like in your example).
If you want a shorter jQuery solution, simply use the .map() method:
var values = $('.aws').map(function () {
return {index: this.value };
}).get();
Try this: https://jsfiddle.net/Twisty/ys889cn6/1/
var obj = [],
temp = {};
$(document).ready(function() {
$(".aws").each(function(i, v) {
obj.push({ "index": $(this).val() });
});
console.log(obj);
});
Much easier to loop this way. Read more: https://api.jquery.com/each/
Somewhat Native
$(document).ready(function() {
var obj = [],
temp = {},
len = $('.aws').length;
for (var i = 0; i < len; i++) {
console.log("Get Value from: .aws[name='item" + (i+1) + "']");
temp["index"] = $(".aws[name='item" + (i+1) + "']").val();
obj.push(temp);
}
console.log(obj);
});
As #PatrickEvans stated, we're just dropping the same object in. Results:
Get Value from: .aws[name='item1']
Get Value from: .aws[name='item2']
[Object { index="2.jpg"}, Object { index="2.jpg"}]
Fixed by using:
$(document).ready(function() {
var obj = [],
temp = {},
len = $('.aws').length;
for (var i = 0; i < len; i++) {
console.log("Get Value from: .aws[name='item" + (i+1) + "']");
obj.push({"index": $(".aws[name='item" + (i+1) + "']").val()});
}
console.log(obj);
});
Related
I have a loop that has a function inside. my target here is to check if the current data inside the loop are still the same for example my array is like this
var data = ['test1','test1','test1','test2'];
now I will check them if the data on that array inside the loop are currently the same. for example like this.
for (var i = 0; i < data.length; i++) {
var value = data[i][0];
console.log(checkifcurrent(value));
}
my problem here is to return checkifcurrent(value) if it still the same like this
function checkifcurrent(value) {
if (currentvalue is still the same as the last one) {
console.log(same);
} else {
console.log(not same);
}
}
I hope you understand tysm for understanding
You can do it like this, no need for a function call.
var data = ['test1','test1','test1','test2'];
lastValue = data[0];
for (var i = 1; i < data.length; i++) {
var currentValue = data[i];
if(lastValue==currentValue){
console.log("Value is same")
}
else
{
console.log("Value is not same")
}
lastValue = currentValue;
}
you can iterate over the data array and compare with all the array elements except the one at the current position.
If it is equals to the current and the index is not the same of the current then it is a duplicate
var data = ['test1','test1','test1','test2'];
for (var i = 0; i < data.length; i++) {
var value = data[i];
for(var j = 0; j < data.length; j++){
//skip the index at position i, because it is the one we are currently comparing
if(i !== j && data[j] === value) {
console.log('another value like: ' + value + ' at position: ' + i + ' has been found at index: ' + j)
}
}
}
Its not very clear about your task, i hope it is checking if the a value present in arr1 is available are not in arr2. If you so,
Loop through all elements in arr1 and check the indexof it
arr1 =[1,2,3,4];
arr2 = [2,3,4,5,6,6];
arr1.forEach((x)=>{if(arr2.indexOf(x)==-1){console.log('unable to find the element'+x)}})
unable to find the element1
var isSame = (function () {
var previous;
return function(value){
var result = value === previous;
previous = value;
return result;
}
})();
Alternatively you can use lodash difference function to compare old and new array.
http://devdocs.io/lodash~4/index#difference
For example:
const _ = require('lodash')
// Save the old array somewhere
let oldArray = ['test1','test1','test1','test2']
let newArray = ['test1','test1','test1','test3']
const areParametersTheSame = !!(_.difference(oldArray, newArray))
I'm trying to iterate through an array using the "TimeStamp" value from each object in that array to return the associated values from a local DB. This below works perfectly for a single iteration if I simply use myArray[0] but as soon as I try and turn it into a loop it doesn't work. I know there's some peculiarity about functions inside loops but don't know what the work around/fix is.
for(var x = 0; x < myArray.length; x++) {
tx.executeSql("SELECT * FROM table WHERE entryreference = '"+myArray[x].TimeStamp+"' ", [], function(tx,results){
var tempArray = [];
var len = results.rows.length;
for (var i = 0; i < len; i++){
var tempObject = {
"Value": results.rows.item(i).value
}
tempArray.push(tempObject);
}
myArray[x].embeddedArray = tempArray;
});
};
Give a temporary scope to the code inside loop for each iteration. Previously, problem was with the value of x. The same mysql query for x=myArray.length-1 was being executing myArray.length times. I think it's fixed with this...
for(var x = 0; x < myArray.length; x++) {
(function(x){
tx.executeSql("SELECT * FROM table WHERE entry reference = '"+myArray[x].TimeStamp+"' ", [], function(tx,results){
var tempArray = [];
var len = results.rows.length;
for (var i = 0; i < len; i++){
var tempObject = {
"Value": results.rows.item(i).value
}
tempArray.push(tempObject);
}
myArray[x].embeddedArray = tempArray;
});
})(x);
};
Even if you succeed to correct your code, it is terribly inefficient, since you are running an SQL query for each value in myArray.
You have to do this in two steps:
building the WHERE part of your query by iterating, probably using an IN condition.
Executing and processing your query.
The problem is that the variable "x" is shared by all the callback functions created in the loop, and by the time the callbacks are actually invoked the value of "x" will be one greater than the length of your array. To get around that problem, you have to encapsulate the construction of the callback functions with another function so that each callback has a reference to the "embedded" array to be built:
function makeCallback(target) {
return function(tx, results) {
var tempArray = [];
var len = results.rows.length;
for (var i = 0; i < len; i++) {
var tempObject = {
"Value": results.rows.item(i).value
}
tempArray.push(tempObject);
}
target.embeddedArray = tempArray;
};
}
for (var x = 0; x < myArray.length; x++) {
tx.executeSql("SELECT * FROM table WHERE entryreference = '" + myArray[x].TimeStamp + "' ", [],
makeCallback(myArray[x]));
};
Each callback gets a reference to the element of "myArray" that is to be updated with the query results. That "target" parameter will be distinct for each callback.
I want to write a function that takes an array such as:
var columns = ['distance', 'times', 'acceleration']
Then from this array, I want to generate something like this:
[{id: id_0, distance: 0, times: 0, acceleration: 0}, {id: id_1, distance: 1, times: 1, acceleration: 1}]
Notice that we have 2 objects here, but I want it to be whatever number I pass in to my parameter. Here is what I have:
generateData: function(rows, columns) {
var generatedData = [];
for (var i = 0, rowLen = rows.length; i < rowLen; i++) {
for (var n = 0; i < columns.length; n++) {
// not sure how to construct an object here from looping through my columns array
generatedData.push({
id: 'id_ + n',
// confused here
});
}
return generatedData;
}
}
This is the perfect place to dynamically create your own function. Try this:
function createArrayOfObjects(columns, count) {
var objectProps = new Array(columns.length);
for (var i = 0; i < columns.length; i++){
//":j" will be the variable j inside the dynamic function
objectProps[i] = columns[i] + ":j";
}
var funcBody = "var arr = new Array(count);" +
"for(var j = 0; j < count; j++){" +
"arr[j] = {" + objectProps.join(',') + "};" +
"}" +
"return arr;";
//Create a new function and call it with count as the parameter, returning the results
return new Function("count", funcBody)(count);
}
var count = 10;
var columns = ['distance', 'times', 'acceleration'];
createArrayOfObjects(columns.concat('id'), count);
This has the benefit of only having to loop over the columns array once where other solutions require nested loops.
JSPerf
I am giving you away the initial non-optimized solution. Its upto you to do the optimizations.
generateData: function(rows, columns) {
var generatedData = [];
for (var i = 0; i < rows.length; i++) {
var myObj = {};
myObj["id_" + i] = i;
for (var n = 0; n < columns.length; n++) {
myObj[columns[n]] = i;
}
generatedData.push(myObj);
}
return generatedData;
}
A functional approach that will take the object properties from the passed in array, instead of hard-coding them, might look something like this inside the for loop to populate an array named 'rows' with property names coming from the values of an array named 'cols':
cols.forEach(function(cv, ci, ca) { rows[ri][cv] = ri; });
See the snippet for a full example. Note that, in this example, I'm just shoving the current index of "rows" into the object as the property value.
var columns = ['distance', 'times', 'acceleration'];
function generateData(numRows, cols) {
rows = new Array(numRows);
for(ri=0; ri < rows.length; ri++) {
rows[ri] = { id: ri };
cols.forEach(function(cv, ci, ca) {
rows[ri][cv] = ri;
});
}
return rows;
}
data = generateData(5, columns);
console.log(data);
I want to print a key: value pair from javascript object. I can have different keys in my array so cannot hardcode it to object[0].key1
var filters = [{"user":"abc"},{"application":"xyz"}];
console.log(Object.keys(filters[0])[0]); // prints user
var term = (Object.keys(filters[0])[0]);
console.log(filters[0].term); // prints undefined
How can i print the value of the key
for (var key in filters[0]){
console.log( key + ": " + filters[0][key]);
}
Or if you want to print all the values of filters
for (var i in filters){
console.log(i);
for (var key in filters[i]){
console.log( key + ": " + filters[i][key]);
}
}
##On #mplungjan 's comment
filters.forEach(function(obj, index){
console.log(index);
for (var key in obj){
console.log(key, obj[key]);
}
});
This is looking for a term property on filters[0]:
console.log(filters[0].term);
What you actually want to do is use the value of term (in your example that will be "user") as the property identifier:
console.log(filters[0][term]);
for loop for array and for..in iteration for object:
var filters = [{ "user": "abc"}, {"application": "xyz"}];
for (var i = 0; i < filters.length; i++) { // the plainest of array loops
var obj = filters[i];
// for..in object iteration will set the key for each pair
// and the value is in obj[key]
for (var key in obj) {
console.log(key, obj[key])
}
}
ES6
[{ "user": "abc"}, {"application": "xyz"}].forEach(
obj => console.log(Object.entries(obj).flat())
)
You can access the value using array syntax
var filters = [{"user":"abc"},{"application":"xyz"}];
console.log(Object.keys(filters[0])[0]); // prints user
var term = (Object.keys(filters[0])[0]);
console.log(filters[0][term]);// prints abc
Lets say that we have a mode object that has some strings in it for example. If we were to do MODE.toString() with just alpha, beta, gamma in the object, what will be returned is [object Object] which is not useful.
Instead, lets say we wanted to get something nice back like Normal, Sepia, Psychedelic. To do that, we could add a toString: function(){...} to our object that will do just that. One catch to this however is that if we loop through everything in the object, the function it self will also be printed, so we need to check for that. In the example I'll check toString specifically, however, other checks like ... && typeof MODE[key] == "string" could be used instead
Following is some example code, calling MODE.toString(); will return Normal, Sepia, Psychedelic
var MODE = {alpha:"Normal", beta:"Sepia", gamma:"Psychedelic",
toString: function() {
var r = "";
for (var key in MODE) {
if (MODE.hasOwnProperty(key) && key != "toString") {
r+= r !== "" ? ", ":"";
r+= MODE[key];
}
}
return r;
}
};
if you want get all keys in array of object, you can try this one mybe
let temp = []
let keys = []
let result = []
for (let i = 0; i < data.length; i++) {
temp = Object.keys(data[i])
for (let j = 0; j < temp.length; j++) {
if(!keys.includes(temp[j])){
keys.push(temp[j])
}
}
temp = []
}
for (let i = 0; i < data.length; i++) {
for (let j = 0; j < keys.length; j++) {
if(data[i][keys[j]] == undefined){
data[i][keys[j]] = ""
}
}
}
return data
or this one if you want take the key from same array 2dimension
function convertObj(arr){
let arrResult = []
for (let i = 1; i < arr.length; i++) {
let obj={}
for (let j = 0; j < arr[0].length; j++) {
obj[arr[0][j]] = arr[i][j]
}
arrResult.push(obj)
}
return arrResult
}
If you want to print key and value, even for nested object then you can try this function:
function printObjectData(obj, n = 0){
let i = 0;
var properties = Object.keys(obj);
let tab = "";
for(i = 0; i < n; i++)
tab += "\t";
for(i = 0; i < properties.length; i++){
if(typeof(obj[properties[i]]) == "object"){
console.log(tab + properties[i] + ":");
printObjectData(obj[properties[i]], n + 1);
}
else
console.log(tab + properties[i] + " : " + obj[properties[i]]);
}
}
printObjectData(filters);
and the solution will look like this:
0:
user : abc
1:
application : xyz
and if you want to remove 0: and 1:
then simply remove
console.log(tab + properties[i] + ":");
after the if statement
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Array value count javascript
I have an array which contains several duplicates, what I'm trying to achieve is to count how many duplicates each unique string has in this one array.
The array looks something like this
array = ['aa','bb','cc','aa','ss','aa','bb'];
Thus I would like to do something like this
if (xWordOccurrences >= 5) {
// do something
}
But I'm not sure how I would code this.
I was thinking, create an object with each unique string, then loop through the original array, match each string with it's object and increment it's number by 1, then loop over the object to see which words had the most duplicates...
But this seems like an over complexe way to do it.
You can use an object which has keys of the Array's values and do something like this
// count everything
function getCounts(arr) {
var i = arr.length, // var to loop over
obj = {}; // obj to store results
while (i) obj[arr[--i]] = (obj[arr[i]] || 0) + 1; // count occurrences
return obj;
}
// get specific from everything
function getCount(word, arr) {
return getCounts(arr)[word] || 0;
}
getCount('aa', ['aa','bb','cc','aa','ss','aa','bb']);
// 3
If you only ever want to get one, then it'd be more a bit more efficient to use a modified version of getCounts which looks similar to getCount, I'll call it getCount2
function getCount2(word, arr) {
var i = arr.length, // var to loop over
j = 0; // number of hits
while (i) if (arr[--i] === word) ++j; // count occurance
return j;
}
getCount2('aa', ['aa','bb','cc','aa','ss','aa','bb']);
// 3
Try this function:
var countOccurrences = function(arr,value){
var len = arr.length;
var occur = 0;
for(var i=0;i<len;i++){
if(arr[i]===value){
occur++;
}
}
return occur;
}
var count = countOccurrences(['aaa','bbb','ccc','bbb','ddd'],'bbb'); //2
If you want, you can also add this function to the Array prototype:
Array.prototype.countOccurrences = function(value){
var len = this.length;
var occur = 0;
for(var i=0;i<len;i++){
if(this[i]===value){
occur++;
}
}
return occur;
}
How about you build an object with named property?
var array = ['aa','bb','cc','aa','ss','aa','bb'];
var summary = {};
var item = '';
for ( i in array){
item = array[i];
if(summary[item]){
summary[item] += 1;
}
else{
summary[item] = 1;
}
}
console.log( summary );
summary will contain like this
{aa: 3, bb: 2, cc: 1, ss: 1}
which you could then iterate on and then sort them later on if needed.
finally to get your count, you could use this summary['aa']
<script type="text/javascript">
var array = ['aa','bb','cc','aa','ss','aa','bb'];
var myMap = {};
for(i = 0; i < array.length; i++) {
var count = myMap[array[i]];
if(count != null) {
count++;
} else {
count = 1;
}
myMap[array[i]] = count;
}
// at this point in the script, the map now contains each unique array item and a count of its entries
</script>
Hope this solves your problem
var array = ['aa','bb','cc','aa','ss','aa','bb'];
var dups = {};
for (var i = 0, l = array.length; i < l; i++ ) {
dups[array[i]] = [];
}
for (str in dups) {
for (var i = 0, l = array.length; i < l; i++ ) {
if (str === array[i]) {
dups[str].push(str);
}
}
}
for (str in dups) {
console.log(str + ' has ' + (dups[str].length - 1) + ' duplicate(s)');
}
This function may do everything you need.
function countDupStr(arr, specifier) {
var count = {}, total = 0;
arr.forEach(function (v) {
count[v] = (count[v] || 0) + 1;
});
if(typeof specifier !== 'undefined') {
return count[specifier] - 1;
}
Object.keys(count).forEach(function (k) {
total += count[k] - 1;
});
return total;
}
Each value in the array is assigned and incremented to the count object. Whether or not a specifier was passed, the function will return duplicates of that specific string or the total number of duplicates. Note that this particular technique will only work on string-coercible values inside your arrays, as Javascript can only index objects by string.
What this means is that during object assignment, the keys will normalize down to strings and cannot be relied upon for uniqueness. That is to say, this function wouldn't be able to discern the difference between duplicates of 3 and '3'. To give an example, if I were to perform:
var o = {}, t = {};
o[t] = 1;
console.log(o);
The key used in place of t would eventually be t.toString(), thus resulting in the perhaps surprising object of {'[object Object]': 1}. Just something to keep in mind when working with Javascript properties.
I saw this post about it, perhaps it can help:
http://ryanbosinger.com/blog/2011/javascript-count-duplicates-in-an-array/