print an array of objects in javascript - javascript

Hello I need help accessing elements of objects in my JavaScript
What's the error of this one
var people = [
{
name: "Jake",
age: 20
},
{
name: "John",
age: 23
},
{
name: "Mike",
age: 21
},
]
for (var i=0; i < 3 ;i++)
document.getElementById("myDiv").innerHTML += "Name: " + people[i].name + "Age: "+ people[i].age +"\n";
I only need to write to the div the values of the array of objects

There was nothing wrong with your Javascript. Check if you have written everything correct for myDiv. Here is my example and it worked fine.
Remember to put a <br> tag instead of \n and " Age: " instead of "Age: ". Good luck!
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<div id="myDiv">
<div>
</body>
</html>
<script>
var people = [
{
name: "Jake",
age: 20
},
{
name: "John",
age: 23
},
{
name: "Mike",
age: 21
},
]
for (var i=0; i < 3 ;i++)
document.getElementById("myDiv").innerHTML += "Name: " + people[i].name + " Age: "+ people[i].age + "<br>";
</script>

Related

Not able to traverse array of objects in javascript.Got output for first element only

var persons = new Array();
var person = {
firstname: "Padma",
Id: 1,
Country: "India"
};
persons.push(person);
persons.push([person = {
firstname: "Balaji",
Id: 3,
Country: "India"
}]);
persons.push([person = {
firstname: "Sivasree",
Id: 2,
Country: "India"
}]);
document.getElementById("demo").innerHTML = persons.length;
$.each(persons, function(key, value) {
console.log(value.firstname + " " + value.Country + "\n");
});
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<h2>JavaScript Objects</h2>
<p>JavaScript uses names to access object properties.</p>
<p id="demo">
</body>
</html>
In your current code you are passing JSON Array inside JSON Object and that JSON Object inside outer JSON Array but your structure should look like [{},{}..] so you can just use persons.push({.. to push object inside main array.
Demo Code:
var persons = new Array();
var person = {
firstname: "Padma",
Id: 1,
Country: "India"
};
persons.push(person);
persons.push({
firstname: "Balaji",
Id: 3,
Country: "India"
}); //this is same as above pushing json object inside json array
persons.push({
firstname: "Sivasree",
Id: 2,
Country: "India"
});
document.getElementById("demo").innerHTML = persons.length;
$.each(persons, function(key, value) {
console.log(value.firstname + " " + value.Country + "\n");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="demo"></div>

Compare these simple javascript code related to object

I have written this code can anyone tell what I have written is correct or not.
var employee = {
name: "John Smith",
job: "Programmer",
age: 31,
printing: function(){
for (just in employee){
alert(this.emloyee(just)"is"this.employee[just])
}
}
}
And tell me that the upper code can work the same.
var employee = {
name: "John Smith",
job: "Programmer",
age: 31,
showAlert: function(){
alert("Name is " + this.name);
alert("Job is " + this.job);
alert("Age is " + this.age);
}
}
employee.showAlert()
It seems you are looking for
var employee = {
name: "John Smith",
job: "Programmer",
age: 31,
showAlert() {
for (const just in this) {
if (typeof this[just] != "function") {
alert(just + " is " + this[just])
}
}
},
};
employee.showAlert()
Notice the const declaration in the loop, the usage of the property name just instead of employee(just), the string concatenation with +, and the use of this instead of employee.
Also the showAlert method itself is just a property that gets enumerated by the for … in loop, so I added a condition to only alert non-function properties.

Using forEach() on an Array of Objects

I know how to get all the information on the web page another way, but I am trying to get it on the web page with the forEach() method to learn something new. This is my first time using the forEach() method can someone please tell what I am doing wrong? Everything but the values get printed onto the web page.
let students = [
{ name: "Milla Jovovich", track: "Fullstack JavaScript", achievements: 5, points: 50 }
,{ name: "Bjon Aarseth", track: "iOS Development", achievements: 7, points: 70 }
,{ name: "Varg Oystein", track: "Front End Development", achievements: 12, points: 120 }
,{ name: "Wilhelm Striepe", track: "Software Engineering", achievements: 9, points: 90 }
,{ name: "Anders Hansen", track: "Data Science", achievements: 22, points: 220 }
] ;
let message = "";
let student;
let search;
function print(message) {
let outputDiv = document.getElementById("output") ;
outputDiv.innerHTML = message ;
}
students.forEach(function(myElement) {
for(let key in myElement) {
myElement += "<h2>Student: " + myElement[key] + "</h2>" ;
myElement += "<p>Track: " + myElement[key] + "</p>" ;
myElement += "<p>Achievements: " + myElement[key] + "</p>" ;
myElement += "<p>Points: " + myElement[key] + "</p>" ;
}
print(myElement) ;
}) ;
<div id="output">
You have a few issues:
Your inner for-loop is redundant as it adds the same value to every information block. Instead, you can remove it and access only the required keys for each of your objects (using dot-notation).
You are trying to concatenate a string with your object when you do myElement += "string" as myElement represents a given object in your array. Instead, you can use your empty string (message) and add to that at each iteration of your loop.
Once you have done that, your message variable will contain the mark-up you need to print once your .forEach loop is complete, and so you can move the print() line to be outside your for loop.
See example below:
let students = [{
name: "Milla Jovovich",
track: "Fullstack JavaScript",
achievements: 5,
points: 50
},
{
name: "Bjon Aarseth",
track: "iOS Development",
achievements: 7,
points: 70
},
{
name: "Varg Oystein",
track: "Front End Development",
achievements: 12,
points: 120
},
{
name: "Wilhelm Striepe",
track: "Software Engineering",
achievements: 9,
points: 90
},
{
name: "Anders Hansen",
track: "Data Science",
achievements: 22,
points: 220
}
];
let message = "";
function print(message) {
let outputDiv = document.getElementById("output");
outputDiv.innerHTML += message;
}
students.forEach(function(myElement) {
message += "<h2>Student: " + myElement.name + "</h2>";
message += "<p>Track: " + myElement.track + "</p>";
message += "<p>Achievements: " + myElement.achievements + "</p>";
message += "<p>Points: " + myElement.points + "</p>";
});
print(message);
<div id="output"></div>
You don't need to iterate over your element with for...in. The forEach is enough.
let students = [{
name: "Milla Jovovich",
track: "Fullstack JavaScript",
achievements: 5,
points: 50
},
{
name: "Bjon Aarseth",
track: "iOS Development",
achievements: 7,
points: 70
},
{
name: "Varg Oystein",
track: "Front End Development",
achievements: 12,
points: 120
},
{
name: "Wilhelm Striepe",
track: "Software Engineering",
achievements: 9,
points: 90
},
{
name: "Anders Hansen",
track: "Data Science",
achievements: 22,
points: 220
}
];
let message = "";
let student;
let search;
function print(message) {
let outputDiv = document.getElementById("output");
outputDiv.innerHTML = message;
}
message = ""; //declare your "message" here, the content of output
students.forEach(function(myElement) {
message += "<h2>Student: " + myElement.name + "</h2>";
message += "<p>Track: " + myElement.track + "</p>";
message += "<p>Achievements: " + myElement.achivements + "</p>";
message += "<p>Points: " + myElement.points + "</p>";
});
print(message); // print "message" when all students have been added to the variable
<div id="output"></div>

Want to achieve functionality by using Javascripts map,reduce,foreach,filter methods

Please help me to write better code.
Suppose I have a JavaScript array like below:
var students = [
{ firstname: "stud1", lastname: "stud2", marks: "60" },
{ firstname: "stud3", lastname: "stud4", marks: "30" },
{ firstname: "stud5", lastname: "stud6", marks: "70" },
{ firstname: "stud7", lastname: "stud8", marks: "55" },
{ firstname: "stud9", lastname: "stud10", marks: "20" },
];
On page I want to show data in two parts, 1)Students who got marks >= 40 2)Students who got marks < 40
By using for loop I done this functionality easily as below.
var data = "";var data1 = "";
for (var i = 0; i < students.length; i++ )
{
if(students.marks >= 40){
data += = students.firstname + " " + students.lastname; //actual data in html div tag
....
}else{
data1 += = students.firstname + " " + students.lastname;
}
}
I want to achieve same functionality by using JavaScript methods like map, reduce, foreach, filter etc. (want to improve my JavaScript knowledge)
Don't know exactly which method is useful for such functionality.
Used map method and tried to display data, but there is a trailing , at the end of each object/array.
Can anyone please help/guide me to write proper code?
Here is solution using filter and forEach methods, using callback functions.
See references here :
filter method
var students = [
{ firstname: "stud1", lastname: "stud2", marks: "60" },
{ firstname: "stud3", lastname: "stud4", marks: "30" },
{ firstname: "stud5", lastname: "stud6", marks: "70" },
{ firstname: "stud7", lastname: "stud8", marks: "55" },
{ firstname: "stud9", lastname: "stud10", marks: "20" },
];
students.filter(function(item){
return item.marks>=40;
}).forEach(function(item){
div=document.getElementById('persons');
div.innerHTML+=item.firstname+' '+item.lastname+'<br>';
});
<div id="persons"></div>
You could use a single loop and add the information with predicate as index. Later join the elements for getting a sting for each element.
var students = [{ firstname: "stud1", lastname: "stud2", marks: "60" }, { firstname: "stud3", lastname: "stud4", marks: "30" }, { firstname: "stud5", lastname: "stud6", marks: "70" }, { firstname: "stud7", lastname: "stud8", marks: "55" }, { firstname: "stud9", lastname: "stud10", marks: "20" }],
predicate = function (o) { return o.marks >= 40; },
result = [[], []];
students.forEach(function (a) {
result[+predicate(a)].push(a.firstname + ' ' + a.lastname);
});
result = result.map(function (a) { return a.join(', '); });
console.log(result);

Parse Database JavaScript and PhoneGap

I've been working on an restaurant app that should get the menu from an online database.
This is how I currently and "Manually" populate the menu:
Controller.html
$scope.menu = [{
name: 'Espresso',
price: 27,
qty: 1,
desc: "One shot of espresso prepared with 7 grams of ground coffee in a single portafilter. The shot should be 1 ounce of liquid. You have two choices with espresso: ristretto, a very short or “restrained” shot, brewed at less than 2/3 of a demitasse, or luongo, a long pull of espresso brewed so the liquid should be more than 2/3 of a demitasse.",
img: "img/espresso.png",
active: false,
sizes: [{name: "Small", price: 0, active:false},
{name: "Medium", price: 5, active:false},
{name: "Large", price: 10, active:false}],
flavors: [{name: 'Vanilla', price: 8, active: false},
{name: 'Almond', price: 8, active: false},
{name: 'Hazelnut', price: 8, active: false},
{name: 'Caramel', price: 8, active: false}]
}];
However I can't seem to achieve populating this using Parse, how would I approach this using a query as the following (Which is a working query).
Index.html
<script type="text/javascript">
Parse.initialize("vGoJDvwwfZBiUFcwfkee7M5vCqL7lLxCgKIFJXDc", "6VRlos6qppaek1uDPPLqpHtmB3fHefOJMqYJNxj9");
var DrinkMenu = Parse.Object.extend("DrinkMenu");
var query = new Parse.Query(DrinkMenu);
query.find({
success: function(results) {
alert("Successfully retrieved " + results.length + " items.");
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
var object = results[i];
alert(object.id + ' - ' + object.get('name'));
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
</script>
You can notice I can get the variables needed for each item, in this case the name of the first result, which I display in an alert.
Any help is appreciated!
After Parse.initialize, create a variable, like this:
var arrMenu = [];
then change the line alert(object.id + ' - ' + object.get('name')); to
arrMenu.push({
name: object.get('name'),
price: object.get('price'),
qty: object.get('qty'),
desc: object.get('desc'),
img: object.get('img'),
active: object.get('active'),
sizes: object.get('sizes'),
flavors: object.get('flavor')
});
I am supposing that you are storing the info in the Parse Collection with the structure you mentioned. If it is different, let me know.
And, after the brack the closes the for, you add:
$scope.menu = arrMenu;
I hope it helps!

Categories

Resources