so I would like to access an an array i created in a previous function. and then in id1,id2,id3, i would Like to create a new property and give that property a value. I thought I have an idea of what I should do but what Im doing is not working. I get the error IdArray is undefined.
HTML:
<p id="show_me"></p>
<button onclick="ObjectArray()">click me</button>
<p id="added"></p>
<button onclick="Added()">Add</button>
javascript previous function:
var ObjectArray = function() {
// object literal
var id1 = {
firstName: "John",
lastName: "Doe",
id: "12345"
};
// keyword new
var id2 = new Object;
id2.firstName = "Adam";
id2.lastName = "Bakely";
id2.id = "abcdef";
// object constructor
function employee(first, last, id) {
this.firstName = first;
this.lastName = last;
this.id = id;
}
var id3 = new employee("Dallas", "Star", "abc123");
//create an array
var IdArray = [id1, id2, id3];
}
javascript new function:
function Added(IdArray, sex){
IdArray.push({sex : sex})
IdArray[0].sex = "male";
document.getElementById("added").innerHTML = IdArray[0];
}
im lost, so how do I access the array from the previous function and add to it?
You do not have access to variables in other functions, you can however access variable declared above your functions. Your real problem is a failure to understand Constructors, which will greatly benefit you in the future. Check this out:
function Employee(id, firstName, lastName, middleName){
this.id = id; this.firstName = firstName; this.lastName = lastName;
this.middleName = middleName;
this.notes = [];
this.getFullName = function(){
var mn = this.middleName ? ' '+this.middleName : '';
return this.firstName+mn+' '+this.lastName;
}
this.createNote = function(note){
this.notes.push(note);
return this;
}
this.getNotesString = function(delimiter){
return this.notes.join(delimiter);
}
}
var employee1 = new Employee('abc123', 'Joe', 'Schmoe');
employee1.createNote('Note You Want to Store.');
employee1.createNote('Just Another Test Note.');
var employee2 = new Employee('def456', employee1.firstName, 'Smith', 'Walter'); // notice how you access the other instance firstName
console.log(employee1.getFullName());
console.log(employee1.getNotesString('|'));
console.log(employee2.getFullName());
console.log(employee2.createNote('Note 1').createNote('Note 2').createNote('Note 3').getNotesString('|')); // by returning `this` you can access other methods in the same Constructor
You need to either save the IdArray or to return it:
var IdArray;
var ObjectArray = function() {
// object literal
var id1 = {
firstName: "John",
lastName: "Doe",
id: "12345"
};
// keyword new
var id2 = new Object;
id2.firstName = "Adam";
id2.lastName = "Bakely";
id2.id = "abcdef";
// object constructor
function employee(first, last, id) {
this.firstName = first;
this.lastName = last;
this.id = id;
}
var id3 = new employee("Dallas", "Star", "abc123");
//create an array
IdArray = [id1, id2, id3]; //removed the var keyword, so I am using the global variable
}
and then use it.
notice I removed the var keyword so I am using the global IdArray.
The variable IdArray was created inside the function, so it expires when the function ends. If you add the line
var IdArray;
before your first function that will make it global instead. Then reference to IdArray inside either function will refer to the same variable.
I added the IdArray as a property of the window object to give it global scope:
var ObjectArray = function() {
// object literal
var id1 = {
firstName: "John",
lastName: "Doe",
id: "12345"
};
// keyword new
var id2 = new Object;
id2.firstName = "Adam";
id2.lastName = "Bakely";
id2.id = "abcdef";
// object constructor
function employee(first, last, id) {
this.firstName = first;
this.lastName = last;
this.id = id;
}
var id3 = new employee("Dallas", "Star", "abc123");
//create an array
window.IdArray = [id1, id2, id3];
}
Related
I would like to build a method setName that set properties to an existing object.
const firstName = 'John'
const lastName = 'Rambo'
const existingObj = {};
existingObj.setName();
console.log(obj.firstName) // John
I am a bit lost between prototypes, class, and I am not sure where to start.
Shall I do this or is there a better solution ?
const setName = (obj) => {
obj.firstName = 'John'
obj.lastName = 'Rambo'
}
const newObj = {};
setName(newObj);
function Person(first, last) {
this.firstName = first;
this.lastName = last;
}
var john = new Person('John', 'Rambo');
console.log('Johns first name is ' + john.firstName);
You can the basics of JS objects and constructors here: https://www.w3schools.com/js/js_object_constructors.asp
To add a method to an existing object to set these values:
const firstName = 'John'
const lastName = 'Rambo'
const existingObj = {};
existingObj.setName = function(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
console.log('The name is ' + this.firstName + ' ' + this.lastName);
};
existingObj.setName('John', 'Rambo');
Can somebody help me with this, i m new to javaScript and i m stuck at this point.I made an output of certain object within my array ,that output is writing a persons values, within that object(Osoba) there is an array of his friends and all values inside are IDs of each person, http://prntscr.com/i9m2ti how can i make that ID of a friend array ( within the object ) to be a first name and surname of that person which id is in array and when i want to output a certain object so there will be friends[ their names instead of IDs], can someone write me down how can i do that. Thanks for understanding.
class Osoba{
constructor(id,firstName,surname,age,gender,friends){
this._id = id ;
this._firstName = firstName;
this._surname = surname;
this._age = age;
this._gender = gender;
this._friends = friends;
}
get id() {
return this._id;
}
set id(id){
this._id = id;
}
get firstName() {
return this._firstName;
}
set firstName(firstName){
this._firstName = firstName;
}
get surname() {
return this._surname;
}
set surname(surname){
this._surname = surname;
}
get age() {
return this._age;
}
set age(age){
this._age = age;
}
get gender() {
return this._gender;
}
set gender(gender){
this._gender = gender;
}
get friends() {
return this._friends;
}
set friends(friends){
this._friends = friends;
}
}
var osobe = []; // my array
$(function() {
$.getJSON('https://raw.githubusercontent.com/Steffzz/damnz/master/
data.json' , function(data)
{
var json = jQuery.parseJSON(JSON.stringify(data));
for(person of json)
{
var id = person['id'] ;
var firstName = person['firstName'] ;
var surname = person['surname'] ;
var age = person['age'] ;
var gender= person['gender'] ;
var friends = person['friends'] ;
var x = new Osoba(id,firstName,surname,age,gender,friends);
osobe.push(x); //filling array with objects and their values
}
console.log(osobe);
document.write(JSON.stringify(osobe[0])) //output of a certain object
})
});
Assuming json is an array and contains all people you can map over friends array and find the person with that id: person['friends'].map( and json.find(function(person){person.id===friendId});.
Then return an object containing that person's first and last name:
console.log("json is:",JSON.stringify(json,undefined,3));
var friends = person['friends'].map(
function(friendId){
console.log("friendID is:",friendId);
var friend = json.find(function(person){return person.id===friendId;});
console.log("friend is:",JSON.stringify(friend,undefined,2));
return {
firstName:friend.firstName,
surname:friend.surname
}
}
);
Now if that "does not work" could you please specify the output of the logs, any errors and expected results versus actual results?
UPDATE FULL CODE
Since the json is all your data you can pass that into your Osoba constructor. The friends getter will use the data to create an array Osaba items that will have data and friends that will create an array of Osaba ...
class Osoba {
constructor(id, firstName, surname, age, gender, friends, data) {//added data
this._id = id;
this._firstName = firstName;
this._surname = surname;
this._age = age;
this._gender = gender;
this._friends = friends;
this._data = data;//data has all the people
}
get id() {
return this._id;
}
set id(id) {
this._id = id;
}
get firstName() {
return this._firstName;
}
set firstName(firstName) {
this._firstName = firstName;
}
get surname() {
return this._surname;
}
set surname(surname) {
this._surname = surname;
}
get age() {
return this._age;
}
set age(age) {
this._age = age;
}
get gender() {
return this._gender;
}
set gender(gender) {
this._gender = gender;
}
//modified friends getter returning an array of Osoba items
get friends() {
var me = this;
return this._friends.map(
function (friendId) {
var friend = me._data.find(function (person) { return person.id === friendId; });
return new Osoba(
friend.id,
friend.firstName,
friend.surname,
friend.age,
friend.gender,
friend.friends,
me._data
);
}
);
}
set friends(friends) {
this._friends = friends;
}
}
$.getJSON('https://raw.githubusercontent.com/Steffzz/damnz/master/data.json')
.then(
json => {
var people = json.map(
person =>
new Osoba(
person.id,
person.firstName,
person.surname,
person.age,
person.gender,
person.friends,
json
)
);
//you can keep getting friends now, because Osoba is
// creating new Osoba objects based on id's and data you pass in
console.log(people[0].friends[0].friends[0].friends[0]);
}
);
instead of
var friends = person['friends'] ;
try
var friends = [];
var friendIDs = person['friends'] ; //retrieve friendIDs
for(friendID of friendIDs) { //loop over friendIDs
var friend = json[friendID]; //get friend dataset out of the json
friends.push(friend['firstName']); // add friend dataset to friends array
}
I assume here that those friends are in that json aswell. and that the ids represent that index inside that array. if the indexes aren't those ids this won't work. feel free to comment if thats the case and i'll edit my answer.
If i understand correctly you just want to use id for id, firstname, and lastname. so just pass id 3 times instead of firstname and lastname:
var x = new Osoba(id,id,id,age,gender,friends);
~~~~
Ok so what you want is actually that the id property within each friend object be the first and last name of the friend instead of an idea code. So it's basically just the opposite of what i suggested earlier. All you have to do is manipulate what you push to id. There's no obligation on it being the id from the json.
so in your case:
for(person of json){
var id = person['firstName'] + "" + person['surname']; // line to change.
var firstName = person['firstName'] ;
var surname = person['surname'] ;
var age = person['age'] ;
var gender= person['gender'] ;
var friends = person['friends'] ;
var x = new Osoba(id,firstName,surname,age,gender,friends);
osobe.push(x); //filling array with objects and their values
}
I'm building an array dynamically in a test angular app. Basically I have a scope function that generates an array of people and returns the array and I have an ng-repeat on the array. The array is not displaying but I'm not getting any errors in the console either, so idk what's up:
am I calling the getPerson function correctly? If there's a better way to do this do let me know.
heres the fiddle as well
$scope.person = {
firstname: "",
lastname: "",
isActive: true,
fullname: function() {
var personobject;
personobject = $scope.person;
return personobject.firstname
+ " "
+ personobject.lastname;
}
};
$scope.people = function() {
var pplArray = [];
var firstnames = ['abdul','mahmud','gasser','ibtihaj','abudi'];
var lastnames = ['ahmad','samrai','badawi','jasim','ahmad'];
var actives = [true,true,false,true,false];
for (var i = 0; i < firstnames.length; i++) {
pplArray[i] = getPerson(firstnames[i], lastnames[i], actives[i]);
}
return pplArray;
};
$scope.getPerson = function(first, last, active) {
var newPerson = $scope.person;
newPerson.firstname = first;
newPerson.lastname = last;
newPerson.isActive = active;
return newPerson;
};
I've updated your fiddle here : https://jsfiddle.net/7j2khgbj/2/
var myapp = angular.module("myapp", []);
myapp.controller('appCont', function($scope) {
var Person = function(){
this.firstname = "";
this.lastname = "";
this.isActive = true;
};
Person.prototype.fullname = function() {
return this.firstname
+ " "
+ this.lastname;
};
var getPerson = function(first, last, active) {
var newPerson = new Person();
newPerson.firstname = first;
newPerson.lastname = last;
newPerson.isActive = active;
return newPerson;
};
$scope.addPerson = function() {
$scope.people.push({
firstname: $scope.person.firstname,
lastname: $scope.person.lastname
});
$scope.person.firstname = '';
$scope.person.lastname = '';
};
$scope.people = (function() {
var pplArray = [];
var firstnames = ['abdul','mahmud','gasser','ibtihaj','abudi'];
var lastnames = ['ahmad','samrai','badawi','jasim','ahmad'];
var actives = [true,true,false,true,false];
for (var i = 0; i < firstnames.length; i++) {
pplArray[i] = getPerson(firstnames[i], lastnames[i], actives[i]);
}
return pplArray;
})();
/*$scope.people = [
{firstname: 'abdul', lastname: 'ahmad'},
{firstname: 'mahmud', lastname: 'samrai'},
{firstname: 'gasser', lastname: 'badawi'},
{firstname: 'ibtihaj', lastname: 'jasim'},
{firstname: 'abudi', lastname: 'ahmad'},
{firstname: 'ahmad', lastname: 'jasim'},
{firstname: 'abdul', lastname: 'samrai'}
];*/
});
Some problems I saw:
1) $scope.people was a function, not an array (so I simply executed it and saved the result)
2) you were always overwriting the person (you need a Person class that creates new instances for the array element, not overwrite the same instance with new data - that way you'll get the same thing in all the array elements)
3) on $scope you should put things that need to be accessible from the view. Helper functions can just be local in the controller (if you don't want them as services, although as services they are reusable)
4) track by on ng-repeat (in case of duplicate keys)
I was messing with some js on codecadamy and got a bit sidetracked trying to make something work.
In essence I was creating a few objects that are loaded into a controller object and set as properties of it with two functions that print the properties and compare a string to the name property of each object in the controller.
I noticed I can do it if I make the objects in the prototype style and specify a normal function to handle setting the properties like so:
var friends = {};
friends.setUp = function() {
this.friends = [];
for(var i in arguments) {
arguments[i].setUp();
this.friends.push(arguments[i]);
}
};
friends.list = function() {
for(var i in this.friends) {
console.log(this.friends[i]);
}
};
friends.search = function(name) {
for(var i in this.friends) {
if(this.friends[i].firstName === name) {
return this.friends[i];
}
}
};
var bill = {};
bill.setUp = function() {
this.firstName = "Bill";
this.lastName = "Gates";
this.number = "(206) 555-5555";
this.address = ['One Microsoft Way','Redmond','WA','98052'];
};
var steve = {};
steve.setUp = function() {
this.firstName = "Steve";
this.lastName = "Jobs";
this.number = "(206) 555-5555";
this.address = ['1 Infinite Loop','Cupertino','CA','95014'];
};
var mike = {};
mike.setUp = function() {
this.firstname = "Mike";
this.lastname = "Ryd";
this.number = "(800) 555-5555";
this.address = ['redacted'];
};
friends.setUp(bill, steve, mike);
friends.list();
var result = friends.search("Steve");
console.log(result);
However if I do it with constructors It does not work, example:
function bill() {
this.firstName = "Bill";
this.lastName = "Gates";
this.number = "(206) 555-5555";
this.address = ['One Microsoft Way','Redmond','WA','98052'];
};
function steve() {
this.firstName = "Steve";
this.lastName = "Jobs";
this.number = "(206) 555-5555";
this.address = ['1 Infinite Loop','Cupertino','CA','95014'];
};
function mike() {
this.firstname = "Mike";
this.lastname = "Ryd";
this.number = "(800) 555-5555";
this.address = ['redacted'];
};
function friends() {
this.friends = [];
for(var i in arguments) {
this.friends.push(arguments[i]);
}
};
friends.list = function() {
for(var i in this.friends) {
console.log(this.friends[i]);
}
};
friends.search = function(name) {
for(var i in this.friends) {
if(this.friends[i].firstName === name) {
return this.friends[i];
}
}
};
var bill = new bill();
var steve = new steve();
var mike = new mike();
var friends = new friends(bill, steve, mike);
friends.list();
var result = friends.search("Steve");
console.log(result);
I was wondering if this is a limitation of using constructors or am I messing up the syntax somewhere? Thank you!
This doesn't appear to have anything to do with constructors with an unknown number of arguments, but rather you are not assigning methods on your objects appropriately. They need to be put on the prototype so that they will be inherited by all objects that are created by this particular constructor. So in your code, these:
friends.list = function() {...}
friends.search = function() {...}
needs to be changed to:
friends.prototype.list = function() {...}
friends.prototype.search = function() {...}
Like this:
friends.prototype.list = function() {
for(var i = 0; i < this.friends.length; i++) {
console.log(this.friends[i]);
}
};
friends.prototype.search = function(name) {
for(var i = 0; i < this.friends.length; i++) {
if(this.friends[i].firstName === name) {
return this.friends[i];
}
}
};
Then, this code should work fine:
var bill = new bill();
var steve = new steve();
var mike = new mike();
var friends = new friends(bill, steve, mike);
friends.list();
var result = friends.search("Steve");
console.log(result);
And, then the code works as you would expect here: http://jsfiddle.net/jfriend00/ba4me8ua/
FYI, you'll noticed that I changed the way you iterate through the arguments object items to be more array-like and avoid any chance of getting any non-numeric properties in the iteration.
So I'm getting this error; Object # has no method 'carName'
But I clearly do.
Pastebin
I've also tried referencing the car's "model" property with
player.car.model
but that doesn't work, I get a type error. Any ideas? Do you need more info?
function person(name, car) {
this.name = name;
this.car = car;
function carName() {
return car.model;
}
}
var player = new person("Name", mustang);
var bot = new person("Bot", mustang);
var bot2 = new person("Bot 2", mustang);
function makeCar(company, model, maxMPH, tireSize, zeroToSixty) {
this.company = company;
this.model = model;
this.maxMPH = maxMPH;
this.tireSize = tireSize;
this.zeroToSixty = zeroToSixty;
}
var mustang = new makeCar("Ford", "Mustang GT", 105, 22, 8);
var nissan = new makeCar("Nissan", "Nissan 360z", 100, 19, 6);
var toyota = new makeCar("Toyota", "Toyota brandname", 95, 21, 7);
It does not have the method. It has a function that is local to the variable scope of the constructor.
To give each object the function, assign it as a property...
function person(name, car) {
this.name = name;
this.car = car;
this.carName = function() {
return this.car.model;
};
}
Or better, place it on the prototype of the constructor...
function person(name, car) {
this.name = name;
this.car = car;
}
person.prototype.carName = function() {
return this.car.model;
};
Also, mustang isn't initialized when you're passing it to the person constructor.