A program in javascript using constructors - javascript

<script>
<!-- A program to search for a friend from an object -->
var friends = {
bill: {
firstName: "Bill",
lastName: "Gates",
number: "205-555-1111",
address:["One Microsoft Day","Redmond","WA","90852"]
},
steve: {
firstName: "Steve",
lastName: "Jobs",
number: "408-555-2222",
address: ["One Infinite Loop", "Cupertino", "CA", "95014"]
},
wendy: {
firstName: "Wendy",
lastName: "Johnson",
number: "510-555-3333",
address: ["3555 Anyplace drive","New York", "NY","11001"]
}
}
alert(friends["steve"].lastName);
alert(friends.length);
var search = function(name)
{
document.write(name);
for (var nameSearch in friends)
{
alert(nameSearch.firstName);
if(friends[nameSearch].firstName===name)
{
return friends[nameSearch];
}
}
}
search("Wendy");
</script>

Theres a couple things wrong with your code:
Objects do not have a length property so the second alert for friends.length will not work
When you're using for in you are referencing the key of the object, so in this case it will be bill, steve, or wendy so when you do nameSearch.firstName it will be undefined since nameSearch is a string
Finally, the reason that your example is failing is because you're searching against case-sensitive text. wendy != Wendy. Also please keep in mind that triple equals checks the constructor.
To fix your code, you can try just lower-casing all of your search text:
var friends = {
bill: {
firstName: "Bill",
lastName: "Gates",
number: "205-555-1111",
address:["One Microsoft Day","Redmond","WA","90852"]
},
steve: {
firstName: "Steve",
lastName: "Jobs",
number: "408-555-2222",
address: ["One Infinite Loop", "Cupertino", "CA", "95014"]
},
wendy: {
firstName: "Wendy",
lastName: "Johnson",
number: "510-555-3333",
address: ["3555 Anyplace drive","New York", "NY","11001"]
}
};
var search = function(name) {
for (var nameSearch in friends) {
if(friends[nameSearch].firstName.toLowerCase()===name.toLowerCase()) {
return friends[nameSearch];
}
}
}
console.log(search("wendy"));

Related

Iterating through object properties/keys

I'm just starting to learn coding, and i came across this question that i could not understand.
"The second function we'll add will be called search, and it will take a first name as an argument. It will try to match the first name it receives to any of the first names in our friends contact list. If it finds a match, it will log our friend's contact information (firstName, lastName, number, address) to the console."
variables are define as follows :
var friends = {};
friends.bill = {
firstName: "Bill",
lastName: "gates",
number: "1234567",
address: ['bishan','starbucks', 'centertable']
};
friends.steve = {
firstName: "Steve",
lastName: "jobs",
number: "987654",
address: ['orchird', 'ikoma', 'ga']
};
the answer is as follows :
var search = function(name) {
for(var key in friends) {
if(friends[key].firstName === name) {
console.log(friends[key]);
return friends[key];
}
}
};
could someone better explain how did the var "key" came about ? and why can't i just input friends.firstName === name, console.log(friends.name), return friends.name ??
would appreciate if someone could explain thank you.
From OP's comment:
var friends = {};
friends.bill = {
firstName: "Bill",
lastName: "gates",
number: "1234567",
address: ['bishan','starbucks', 'centertable']
};
friends.steve = {
firstName: "Steve",
lastName: "jobs",
number: "987654",
address: ['orchird', 'ikoma', 'ga']
};
friends is a nested object which can also be represented like so:
friends = {
bill: {
firstName: "Bill",
lastName: "gates",
number: "1234567",
address: ['bishan','starbucks', 'centertable']
},
steve: {
firstName: "Steve",
lastName: "jobs",
number: "987654",
address: ['orchird', 'ikoma', 'ga']
}
}
The for..in loop iterates over all keys in the friends object, with the variable key in your case.
why can't i just input friends.firstName === name, console.log(friends.name), return friends.name ??
Because, to do that, you need to have firstName or name as a property in friends. Since those properties are nested inside (name is not event inside the nested objects), there was a for..in loop used.
You have an object friends that has 2 properties bill and steve (those are the keys). Calling friends.bill will return you an object (the value) with firstname, lastname, number, address. You need to iterate all the properties of your object friends to find the one you need
You can use Object.values(obj)
var firstNameInput = "Steve";
var friends = {};
friends.bill = {
firstName: "Bill",
lastName: "gates",
number: "1234567",
address: ['bishan','starbucks', 'centertable']
};
friends.steve = {
firstName: "Steve",
lastName: "jobs",
number: "987654",
address: ['orchird', 'ikoma', 'ga']
};
//Iterates all the friends
Object.values(friends).forEach(function(f){
//Compare the property "firstname" with the input
if(f.firstName === firstNameInput){
//Friend found
console.log(f);
return;
}
});

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);

JavaScript build a dynamic object

I have a var named onversation that contains this:
{
"conversationId": "adbabc54-3308-436d-a48b-932f4010d3c6",
"participantId": "415651e6-f0a5-4203-8019-4f88c3ed9cd5"
}
I also have an object named person that contains this:
{
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
}
What I'd like is to have a combined object called result that looks like this
result {
conversation {
conversationId : adbabc54-3308-436d-a48b-932f4010d3c6,
participantId : 415651e6-f0a5-4203-8019-4f88c3ed9cd5
},
person {
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
}
}
How would I do this dynamically whereby the result object is built using the name of the var 'conversation' and name of the object 'person' ?
Also, the length of either conversation or person can be any length.
Pure JavaScript if possible , but could use underscore etc.
Try it
var result = {
'conversation': conversation,
'person': person
}
Dynamic
var result = {}
result['person'] = person
or
resilt.person = person
If I understand your question correctly, you can use object shorthand notation which is supported in most browsers (Probably all of them, except IE11) for simplifying your solution even more:
var conversation =
{
conversationId : 'adbabc54-3308-436d-a48b-932f4010d3c6',
participantId : '415651e6-f0a5-4203-8019-4f88c3ed9cd5'
};
var person =
{
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
};
var result = { conversation, person }
console.log(result)
EDIT:
If only the variable name changes, and it's properties names stay the same or have some sort of unique key, you can use a for loop on the object's keys.
For example:
var someConversationVariableName =
{
conversationId : 'adbabc54-3308-436d-a48b-932f4010d3c6',
participantId : '415651e6-f0a5-4203-8019-4f88c3ed9cd5'
};
var somePersonVariableName =
{
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
};
var result = { someConversationVariableName, somePersonVariableName }
for (key in result) {
if(result[key]['conversationId']) {
console.log(`Found conversation object. It's name is: ${key}`);
}
else if(result[key]['firstname']) {
console.log(`Found person object. It's name is: ${key}`);
}
}
If you need to defer adding objects, you can also take this approach:
var conversation =
{
conversationId : 'adbabc54-3308-436d-a48b-932f4010d3c6',
participantId : '415651e6-f0a5-4203-8019-4f88c3ed9cd5'
};
var person =
{
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
};
var result = {};
result['conversation'] = conversation;
result['person'] = person;
console.log(result);
This Must work :-
var conversation =
{
"conversationId": "adbabc54-3308-436d-a48b-932f4010d3c6",
"participantId": "415651e6-f0a5-4203-8019-4f88c3ed9cd5"
}
var person=
{
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
}
var result = {
'conversation': conversation,
'person': person
}

I created two different objects in one object. On printing them, only the last modified object is getting displayed. How to create?

var friends=new Object();
friends.bill=new Object();
friends.steve=new Object();
var friends={
bill:{
firstName: "Bill",
lastName: "gates",
number:'040404040',
address: ['bcd','sdad']
}
};
var friends={
steve:{
firstName: "Steve",
lastName: "Jobs",
number:'131313131',
address:['abc','sdsdsd']
}
};
console.log(friends);
the output of this program is all about the object "steve". If I log "friends.steve" it logs as "undefined". I want the output to be two diffrent objects in the object friend.
You are overriding the previously create object.
Rather you should try
var friends=new Object();
friends.bill=new Object();
friends.steve=new Object();
friends.bill={
firstName: "Bill",
lastName: "gates",
number:'040404040',
address: ['bcd','sdad']
};
friends.steve={
firstName: "Steve",
lastName: "Jobs",
number:'131313131',
address:['abc','sdsdsd']
};
console.log(friends);
To store multiple values in a variable you can use the Array.
var bill = {
firstName: "Bill",
lastName: "gates",
number:'040404040',
address: ['bcd','sdad']
}
var steve = {
firstName: "Steve",
lastName: "Jobs",
number:'131313131',
address:['abc','sdsdsd']
}
var friends = [bill, steve];
console.log(friends);
Also, in your code, you are defining the variable friends, which overwrite the variable defined with the same name. Additionally, you can define the class for friend and can create 2 objects from the class.
function Friend(firstname, lastname, number, address)
{
this.firstname = firstname;
this.lastname = lastname;
this.number = number;
this.address = address;
}
var bill = new Friend("Bill", "gates", "address", 040404040 ,['bcd','sdad']);
var steve = new Friend("Steve", "Jobs", "address", 131313131, ['abc','sdsdsd']);
var friends = [bill, steve];
console.log(friends);
In your code you define friends variable and override again in next few lines
'var friends={
bill:{'
This will override the first object and new instance will taking place instead.
Try this code and this will solve your problem
var friends = new Object();
friends.bill = {
firstName: "Bill",
lastName: "gates",
number:'040404040',
address: ['bcd','sdad']
};
friends.steve ={
firstName: "Steve",
lastName: "Jobs",
number:'131313131',
address:['abc','sdsdsd']
};
console.log(friends);

error in a search function in javascript

I am trying to return contact info for "steve", but codecademy is telling me that it is not returning correctly.
It looks like your search function doesn't return contact information for Steve.
I am not able to find any error in this code. Can you help me with finding any syntax or logical errors in the search function that you can see?
var friends = {
bill: {
firstName: "bill",
lastName: "gates",
number :21415,
address: ["mcklsn", "wcnskln"]
},
Steve: {
firstName: "bill",
lastName: "gates",
number: 21415,
address: ["mcklsn", "wcnskln"]
}
};
var list = function (friends)
{
for (bill in friends)
console.log(bill);
for (steve in friends)
console.log(steve);
};
var search = function(name)
{
for (var i in friends)
{
if (friends[i].firstName === name)
{
console.log(friends[i]);
return friends[i];
}
else
console.log("contact doesn't exist!");
}
};
You should really pay attention to what you are writing, don't Ctrl-C Ctrl-V everything blindly. You are not calling your friends in the correct names and I would be offended if someone did that to me. Heck, Steve Jobs would be furious if you called him Bill!
This should work:
var friends = {
Bill: {
firstName: "Bill",
lastName: "Gates",
number: 21415,
address: ["mcklsn", "wcnskln"]
},
Steve: {
firstName: "Steve",
lastName: "Jobs",
number: 21416,
address: ["mcklsnn", "wcnsklnn"]
}
};
search("Bill");
search("Steve");
Yah, because your Steve property object's firstName is set to "bill".
So that code, searching for a match to 'steve' on the firstName property will not find one...because there isn't one. Both of those object's have 'bill' as their firstName property.

Categories

Resources