I have an array containing objects that looks like this:
[{\"user\":\"mcnewsmcfc\",\"num\":11},{\"user\":\"ManCityFNH\",\"num\":7}];
I am then using:
var jsonu = JSON.parse(tweets.replace(/"/g, '\"'));
to remove all the unwanted characters from the array. My question is then how to iterate through the array and (EDIT) use the values of "user" and "num" for each object in the table (EDIT).
This is what I initally have but this does not extract the correct values:
for (var u in jsonu) {
var row = $('<row></row>');
row.append('<th>' + jsonu[u][0] + '</th><td>' + jsonu[u][1] + '</td>');
$('#userTable').append(row);
}
var tweets = '[{\"user\":\"mcnewsmcfc\",\"num\":11},{\"user\":\"ManCityFNH\",\"num\":7}]';
var jsonu = JSON.parse(tweets.replace(/"/g, '\"'));
for (var u in jsonu) {
var row = $('<row></row>');
row.append('<th>' + jsonu[u].user + '</th><td>' + jsonu[u].num + '</td>');
$('#userTable').append(row);
}
since jsonu is an array, u is just the index in the array. jsonu[u] will return back the object at that index in the array, which is a javascript object.
So to access the user and num property, simply call jsonu[u].user and jsonu[u].num
Related
I am creating a store. The way it works is that when I click 'add to cart', I run a function which gets the id of the button. From that id, you can work out the name of the product, get the cost, quantity etc. For simplicity, this is the funciton code:
function getID(a){
var id = a.substring(0, a.length - 4);
var id_quant = document.getElementById(id + '_val').value;
var id_name = document.getElementById(id + '_nme').innerHTML;
console.log(id + " " + id_quant + " " + id_name);
}
You may notice that I remove the last 4 digits from this.id, this is because when I run the PHP to echo all the results, i make the button_id equal to the uid from the database, concatenated with _btn.
What I would then like to do is to push this into an array, or use JSON.
What I am imagining is a nest array like : array[uid][cost], array[uid][name]. I'm just not sure how to do this.
It should be noted that in the function, a is actually this.id:
<button id='1_btn' onclick='getID(this.id)'></button>
I have declared an array above the function, var array = [].
Any help on how to push a nest would be great.
What I would then like to do is to push this into an array, or use
JSON.
You need to use an object
var obj = {};
and set values in this obj from the function as
function getID(a){
var id = a.substring(0, a.length - 4);
var id_quant = document.getElementById(id + '_val').value;
var id_name = document.getElementById(id + '_nme').innerHTML;
obj[ id ] = { quantity : id_quant, name : id_name }; //observe this line
console.log(id + " " + id_quant + " " + id_name);
}
instead of array you should have an object.
var bucket = {};
bucket[someuid] = {
"cost": 500,
"name": "Some Item"
}
Now you can access this simply by,
console.log(bucket[someuid]);
Iterating then is simple
for (item in bucket){ console.log(item['name'], item['cost']) }
Recently Attended the interview, Some one asked the question like below:
var array = [0,1,2,3,4,5];
Output :
temp:
temp1:1
temp22:22
temp333:333
temp4444:4444
temp55555:55555
I tried below code it is working fine but is there any best solution for this example :
array.forEach(function(item,index){
var text ="";
if(index >= 2){
for(var j =1; j <= index; j++){
text += index;
}
console.log("temp"+text + ":" + text);
}else{
console.log("temp"+index + ":" + index);
}
});
Thanks in advance!
Using ES6 template strings and String.prototype.repeat
var array = [0,1,2,3,4,5];
array.forEach(item => {
const text = String(item).repeat(item);
console.log(`temp${text}: ${text}`);
})
And the same code translated into ES5 - this will work in all browsers starting from IE9 and above.
var array = [0,1,2,3,4,5];
array.forEach(function(item) {
var text = Array(item+1).join(item);
console.log("temp" + text + ": " + text);
})
Since String.prototype.repeat does not exist in ES5, there is a bit of a hack to generate a string of specific length with repeating characters:
Array(initialCapacity) will create a new array with empty slots equal to what number you pass in, Array.prototype.join can then be used to concatenate all members of the array into a string. The parameter .join takes is the separator you want, so, for example you can do something like this
var joinedArray = ["a","b","c"].join(" | ");
console.log(joinedArray);
However, in this case, each of the members of the array is blank, since the array only has blank slots. So, upon joining, you will get a blank string, unless you specify a separator. You can leverage that to get a repeat functionality, as you are essentially doing something like this
//these produce the same result
var repeatedA = ["","",""].join("a");
var repeatedB = Array(3).join("b");
console.log("'a' repeated:", repeatedA);
console.log("'b' repeated:", repeatedB);
Using the Array function, you can scale it to any number of repeats you want. The only trick is that you need to add 1 when creating the array, since you get one less character when joining.
You could iterate the array and iterate the count. Then display the new string.
var array = [0, 1, 2, 3, 4, 5];
array.forEach(function (a, i) {
var s = '';
while (i--) {
s += a;
}
console.log ('temp' + s + ':' + s);
});
I have the following:
var students = [{name:"Jordan", age:"6"},{name:"Jake", age:"7"},{name:"Mark", age:"10"}]
I want to generate a string like this:
"Jordan,6|Jake,7|Mark,10"
What is the most efficient way to do this?
I am currently using:
var studentstr = "";
for(var i = 0; i < students.length; i++) {
studentstr = students['name'] + "," + students['age'] + "|"
}
studentstr = studentstr.substring(0, studentstr.length - 1);
Also, performance-wise, if I had an array of 2,000 items, is it "costly" to perform this transformation? The resulting string contains both keys in the object and not a single join on one object in the property.
You can map each student object to a string and then join them all with |:
var studentstr = students.map(function (student) {
return student.name + ',' + student.age;
}).join('|');
Also, performance-wise, if I had an array of 2,000 items, is it "costly" to perform this transformation?
No.
Yes, using string concatenation in a loop is costly. The string grows for each iteration, and each time you have to copy the entire previous string to create the new version. The execution time of the loop grows exponentially to the number of items.
You can put the string for each object in an array, then join them together:
var students = [{name:"Jordan", age:"6"},{name:"Jake", age:"7"},{name:"Mark", age:"10"}];
var items = [];
for (var i = 0; i < students.length; i++) {
items.push(students[i].name + ',' +students[i].age);
}
var str = items.join('|');
// display result in snippet
document.write(str);
map works well for this:
var students = [{name:"Jordan", age:"6"},{name:"Jake", age:"7"},{name:"Mark", age:"10"}];
var result = students.map(function(student) {
return student.name + ',' + student.age;
});
alert(result.join('|'));
Try this and see your console:
var string = '';
for (var s in students) {
string += students[s].name + ', ' + students[s].age + ' | ';
}
console.log(string);
Fiddle: http://jsfiddle.net/80ss0u14/
I do not think it is costly to go on with such approach. It may be the most efficient way to iterate through the data.
Given this JavaScript array:
var list = [1,1,1,2,2,2,2]
I want to know how I can produce an HTML list below that has each unique item in the array and number of times that they appear in the array. I just want to know the JavaScript to produce the data, I can generate the HTML.
1 is x3
2 is x4
I'm confused about how to achieve this. Basically, similar to shopping cart quantity functionality, but using the array.
http://jsfiddle.net/37ab3k00/
Use .reduce to reduce your array to an object of quantities.
var list = [1, 1, 1, 2, 2, 2, 2];
var quantities = list.reduce(function(obj, n) {
if (obj[n]) obj[n]++;
else obj[n] = 1;
return obj;
}, {});
var ul = document.querySelector("ul");
for (var n in quantities) {
ul.appendChild(document.createElement("li")).textContent = n + " has a quantity x" + quantities[n];
}
<ul></ul>
The first argument to .reduce() is a function that gets invoked for each member in the Array.
The second argument is an object that we're going to pass along to each iteration. It gets passed as the first argument to the function we provided, and we always return it so that it always gets passed as that argument. This is called the accumulator.
The n argument to the function we provided is the value of the current member in the list. So what we do is first see if our obj has a truthy n member. If so, it must have been encountered already, so we increment it. If not, we assign it the initial value of 1 to represent the first n that was found for that value.
var list = [1,1,1,2,2,2,2]
var counts = {};
for (var i = 0; i < list.length; i++) {
counts[list[i]] = 1 + (counts[list[i]] || 0);
}
Demo: http://jsfiddle.net/famn4zcL/2/
Add to HTML
var li = '';
for (var el in counts) {
li += '<li>' + el + ' is x' + counts[el] + '</li>';
}
document.getElementById('list').innerHTML = li;
Demo: http://jsfiddle.net/famn4zcL/3/
Another way would be using array of objects (those can be easily upgraded with additional data that you probably would need building products), like so:
HTML:
<span id="display"></span>
JS (plain, no Framework):
var objects = [
{prod:0,quant:00},
{prod:1,quant:11},
{prod:2,quant:22},
{prod:3,quant:33},
{prod:4,quant:44},
{prod:5,quant:55}
];
var list_of_objects = "", display_id = document.getElementById("display");
for (var key in objects) {
if (objects.hasOwnProperty(key)) {
console.log(key);
list_of_objects += '<li>'+objects[key].prod + ' has a qtty x ' + objects[key].quant+'</li>';
}
}
console.log(list_of_objects);
display_id.innerHTML = list_of_objects;
So you could easily upgrade product data with new info, like:
var objects = [
{prod:0,quant:00,url:"http://url00"},
{prod:1,quant:11,url:"http://url11"},
{prod:2,quant:22,url:"http://url22"},
{prod:3,quant:33,url:"http://url33"},
{prod:4,quant:44,url:"http://url44"},
{prod:5,quant:55,url:"http://url55"}
];
JSfiddle to play with: http://jsfiddle.net/7hokfmdu/
var myArray = new Array();
var increment = 0;
myArray.push('Tom Hanks', 'Pierce Brosnan', 'Will Smith', 'Richard Ayoade');
for (actor in myArray) {
console.log(actor + ' is my #' + increment + ' choice.');
increment++;
}
Something is wrong with this for loop, and I believe its 'actor' in the for-in loop. This prints out a number where the name of the actor should be.
Coming from Ruby, this looks like a .each method iterating over each element in the array, but obviously this is going about things a bit differently. Can anyone explain why this isn't working?
Just picked up JS today. Thanks.
Thats not how for ... in works. From that link:
A for...in loop iterates over the properties of an object in an arbitrary order
And:
for..in should not be used to iterate over an Array where index order is important. Array indexes are just enumerable properties with integer names and are otherwise identical to general Object properties. There is no guarantee that for...in will return the indexes in any particular order and it will return all enumerable properties, including those with non–integer names and those that are inherited.
Given that you are passing in an array the properties are the indexes for the items it holds.
This is why you are getting the index and not the name.
If you want to retain order and print the names, you need a "traditional" for loop, like so:
for (var i = 0; i < myArray.length; i++) {
console.log(myArray[i] + ' is my #' + (i+1) + ' choice.');
}
The reason to be careful when using for .. in is it can have unexpected results. Checkout this jsFiddle...
var myArray = new Array();
var increment = 0;
myArray.push('Tom Hanks', 'Pierce Brosnan');
myArray.hello = "what?";
for (actor in myArray) {
alert(actor + ' is my #' + increment + ' choice.');
increment++;
}
for (var i = 0; i < myArray.length; i++) {
alert(myArray[i] + ' is my #' + (i+1) + ' choice.');
}
In this example, the first loop will iterate 3 times, picking up the 'hello' property as well as the rest in the array. While the second only does the 2 formal items in the array.
In that case, the correct code should be
var myArray = new Array(); var increment = 0;
myArray.push('Tom Hanks', 'Pierce Brosnan', 'Will Smith', 'Richard Ayoade');
for (actor in myArray) {
console.log(myArray[actor] + ' is my #' + increment + ' choice.');
increment++; }
it prints out
Tom Hanks is my #0 choice.
Pierce Brosnan is my #1 choice.
Will Smith is my #2 choice.
Richard Ayoade is my #3 choice.
You are seeing the index of the array element.
Remember that arrays are objects.
When using for(var item in object), var item is the key(property) associated with the value.
You are accessing the arrays properties(indexes), not values.
You should consider using the Array Objects buitin method forEach.
myArray.forEach(function(actor)){
console.log(actor + ' is my #' + increment + ' choice.');
increment++;
});
The simple answer is this: for in loops iterate over properties of an object. An array in JavaScript is an object that's indexed. So, your example is actually this:
Array[4]
0: "Tom Hanks"
1: "Pierce Brosnan"
2: "Will Smith"
3: "Richard Ayoade"
length: 4
__proto__: Array[0]
When you use your for/in code,
for (actor in myArray) {
console.log(actor + ' is my #' + increment + ' choice.');
increment++;
}
actor is the property at the time of iteration (0, 1, 2, 3...)
To access the value in your for in loop would require your code to be updated like this:
for (idx in myArray) {
console.log(myArray[idx] + ' is my #' + idx + ' choice.');
}
However, it's considered bad practice to use for in loops to iterate an array. For example, what if I did something like this:
myArray.type = "Actors";
The console log would return something like:
// 'Actors is my type choice'
Probably not the intended output. Instead, for array iteration, take a look at the for loop or forEach method of arrays.
for (var increment = 0, len = myArray.length; increment < len; increment += 1) {
console.log(myArray[increment] + ' is my #' + increment + ' choice.');
}
// or...
myArray.forEach(function(actor, increment) {
console.log(actor + ' is my #' + increment + ' choice.');
});