Am i thinking clearly here in creating a new object? - javascript

let person = {
name:"kevin",
eyeColor:"blue",
age: 34,
address: {
street: "12 havering road",
town: "romford",
house: {
type: "terraced",
bedrooms: 3,
}
},
updateAge: function () {
let age = ++person.age;
return age;
}
};
console.log(person.updateAge());
let details = person.address.house;
alert(details.type);
Hello everyone, I have a burning question in regards to objects. I must say when i am watching tutorials on this , most are unclear as i like to understand concepts instead of just end goal's but i cant seem to find much material in regards to the concepts so after several hours of playing with the console. i have come up with this. I may be completely wrong but need to ask for my sanity. The code above i am imagining var person as the global window object. Address as the document( a property of the window object) . house as the getElementById ( i know thats a method compared to a property but im only focusing on the pathway accessing properties and methods in objects. Then im assuming im assigning all to a varialbe and then .type is like .innerHTML.
So although obviously funcitonally not the same. am i correct in saying including the window global object the pathway to e.g.
var box = window.document.getElementById('box');
box.innerHTML =
IS THE SAME AS
var box = person.address.house;
box.type =
Obvs ignore the functionality but the pathway of creating my own objects, am i correct in saying is a similar setup ?
thanks all

I think I understand what you are asking. window.document.getElementById('box').innerHTML is similar to calling person.address.house.type. However, I must point out that the window object is a built in javascript object and your person object was created by you. The window object is made up of a bunch of properties and methods, which then contains nested properties and methods, which is similar to your person object!
If you ever want to see what properties and methods an object contains you can use console.dir():
console.dir(window);
let person = {
name:"kevin",
eyeColor:"blue",
age: 34,
address: {
street: "12 havering road",
town: "romford",
house: {
type: "terraced",
bedrooms: 3,
}
},
updateAge: function () {
let age = ++person.age;
return age;
}
};
console.dir(person);

Related

Javascript object result has additional character

This question might be ridiculous but I tried searching everywhere but I just can't find a good reference.
Why does some object in javascript has the structure like in the image attached below?
There is t character. And how do I convert the normal object to that form? For instance:
{
key: "training",
amount: 4500,
currency: "PLN",
label: "Training",
}
The character t is the class name of the object that is passed as the value of the key value. As user #Vishnudev mentioned in the comments.
Consider the following code to recreate the JavaScript object and its structure in the image.
Code
class t{
constructor( amount, currency, _sdkType) {
this.amount = amount
this.currency = currency
this._sdkType = _sdkType
}
}
let value = new t(4500, "PLN", "Money")
let object = {
value: value
}
console.log(object)
Output
Result as seen in the browser console.

Filtering an array of objects by user defined properties based on user inputted search term

That title might not make a lot of sense but please bear with me and I'll try to explain what I'm after.
I'm creating an Angular filter component that I can plug and play into various portions of my app. However, the question itself is more of a JavaScript question than an Angular one.
What I want to achieve is quite simple in theory but seems to be hard in practice (at least for me).
I want to give the user the ability to input an array of objects, and an array of object property names. I then want to filter the array of objects by either property 1 OR property 2.
Lets say we have the following setup:
inputtedObjects = [
{name: 'Bruce', gamerTag: 'BruceyBoi', email: 'b.banner#email.com'},
{name: 'Frank', gamerTag: 'BruceIsMyNemesis', email: 'f.francis#yahoo.com'},
{name: 'Steve', gamerTag: 'ScubaSteve', email: 'superstevo#live.com'}
];
filterProperties = ['name', 'gamerTag']
What I then want to do is essentially this operation:
let filteredObjects = inputtedObjects.filter(object =>
object[filterProperties[0]].toLowerCase().includes(searchTerm) ||
object[filterProperties[1]].toLowerCase().includes(searchTerm)
Where the searchTerm is a user inputted field from an input tag in HTML.
This would result in if the user was typing in "bruce" in the input, he would get the top two filtered results returned to him.
I have tried the following code:
let currentObjects = this.objects;
this.filterProperties.forEach(field => {
this.filteredObjects = currentObjects.filter(
object =>
object[field]
.toLowerCase()
.includes(searchTerm.toLowerCase())
);
});
However, the issue with the code above is that it filters as an AND and not an OR in the sense that it would work but if the user wrote "bruce" it would only return the first object as both of the properties must include "bruce" for the above code to work.
Now I can do this with some kind of switch case, as in if the filterProperties array is length 1 then we do:
let filteredObjects = inputtedObjects.filter(object =>
object[filterProperties[0]].toLowerCase().includes(searchTerm)
and if it's of length 2 we do:
let filteredObjects = inputtedObjects.filter(object =>
object[filterProperties[0]].toLowerCase().includes(searchTerm) ||
object[filterProperties[1]].toLowerCase().includes(searchTerm)
Etc.
Now obviously this is not very clean code, nor does it seem very efficient whatsoever. It's also not easy to scale and it would require some kind of error message if the user attempted to input too many "filterProperties" as it would depend on the amount of hardcoded switch case statements (bad code smell already).
What I would want to achieve then is for the user to be able to provide an array of infinite objects of a certain type with potentially hundreds of properties per object. Then the user says, I want to filter on these 6 property names, and then begins to type "test", it would then evaluate objects that match test on any one of these 6 properties provided. Not only objects that match test on all of these properties.
Any ideas on how I could potentially achieve this outcome?
You can use Array.some on the filterProperties array to see if one (or more) of the object properties contains the searchTerm:
inputtedObjects = [{
name: 'Bruce',
gamerTag: 'BruceyBoi',
email: 'b.banner#email.com'
},
{
name: 'Frank',
gamerTag: 'BruceIsMyNemesis',
email: 'f.francis#yahoo.com'
},
{
name: 'Steve',
gamerTag: 'ScubaSteve',
email: 'superstevo#live.com'
}
];
filterProperties = ['name', 'gamerTag'];
searchTerm = 'bruce';
filteredObjects = inputtedObjects.filter(object =>
filterProperties.some(p => object[p].toLowerCase().includes(searchTerm))
);
console.log(filteredObjects);
Try this, adds into a list when a match is found on any field instead of overwriting it.
let filtered = [];
inputtedObjects.forEach(obj => {
console.log(obj.name)
for (let field of filterProperties) {
if (obj[field].toLowerCase().includes(searchTerm.toLowerCase())) {
console.log(obj.name, field)
filtered.push(obj);
break;
}
}
});
https://jsfiddle.net/k1bj8zof/

How do I create user defined types (ala C#) to use in objects in JavaScript?

In C#, I can create a class that acts as a user-defined type, such as:
Public Class FullName
{
string FirstName;
string LastName;
}
Public Class Address
{
string Line1;
string Line2;
string City;
string State;
string Zip;
}
and then I can create:
Public Class Person
{
FullName Name;
Address HomeAddress;
Address WorkAddress;
}
This allows me to reference the data like:
Person Bob;
Bob.WorkAddress.Line1 = "123 Sycamore Rd";
Bob.HomeAddress.Line1 = "1313 MockingBird Ln";
Bob.FullName.LastName = "Smith";
etc...
Ultimately, I want to create a 2D array of Person, so I don't want to hardcode (pre-populate?) the data until I know what it is.
I'd like to be able to do the same thing in JavaScript (specifically node.js), but can't seem to find an obvious way of doing so. Is this just fundamentally the wrong approach, or am I just missing something?
In Javascript you can create data objects directly (no classes):
var bob = {
workAddress: { line1: "123 Sycamore" },
fullName: { lastName: "Smith" }
};
It's also possible to create a class, but it's usually not necessary for mere data objects.
Ultimately, I want to create a 2D array of Person, so I don't want to hardcode (pre-populate?) the data until I know what it is.
You can create an array and later add persons to it:
var persons = [];
...
persons.push(bob);
For a 2D array, create an array to contain your person arrays:
var persons2D = [];
...
persons2D.push(persons);
A really good example of javascript objects and their notation would be JSON.org
Here is an object that has 2 string properties, and a 3rd property which is an array. One slight difference is that because javascript is not strongly typed, the "residents" property could just be a simple string or an array. So you have to be careful when parsing as any property could be either a string or another array.
var household = {
address: "1234 N 56th st"
, city: "somewhere"
, residents: [
{ Name: "My Name" }
, { Name: "My Alias" }
]
};
Now depending on how you are sourcing the data, you can use the javascript or JSON (de)serialize methods within C# to populate.

Access object properties after they are assigned by another function

I'm new to Javascript, and I'm learning how to use OOP principals. I'm stuck on assigning object properties and then accessing them later.
Let's say I have this function that assigns properties to an object "Car".
function assignProps()
{
Car.size="small";
Car.cost="expensive";
}
The object Car with empty properties because they are assigned from the function.
var Car =
{
size:"",
cost:"",
returnSize: function()
{
return this.size;
},
returnCost: function()
{
return this.cost;
},
}
Now, I want to call the function that assigned the value, and then access Car's properties. I tried doing this, but it obviously failed:
function accessProps()
{
assignProps();
console.log(Car.returnSize());
console.log(Car.returnCost());
}
Any help would be appreciated. I have a feeling that this might have to do with constructors or prototypes, but since there are so many ways to create custom objects in Javascript, the documentations are very confusing.
EDIT: By "fail" I mean that it outputs the blank instead of the newly assigned value
EDIT: I tried doing it this way as well, and it yielded the same result.
You have some errors in your code:
var Car = {
size:"",
cost:""
}
And if you look at this fiddle: http://jsfiddle.net/JskBy/
It works as expected.
Full code:
function assignProps() {
Car.size="small";
Car.cost="expensive";
}
var Car ={
size:"",
cost:""
}
function accessProps(){
assignProps();
console.log(Car.size);
}
assignProps();
accessProps();
You have a syntax error on your car object initialization, should be
var Car = { size: "", cost: "" };
Line 18, column 14: Extra comma.
Line 20, column 2: Missing semicolon.
Try to get a developing tool with JSLint/JSHint built-in (e.g. Notepad++ with add-on), it might help you with debugging problems like this.

People guesser program with JavaScript objects

I'm trying to learn JavaScript, and so I'm doing this project to practice. I'm trying to figure out how the objects and all that work. Basically what I want, is a list of people, as objects, with certain properties assigned to each. Then it to ask a bunch of questions until it guesses the person you're thinking of. I've searched around, but can't really find exactly how to do this. This is what I have so far:
function person(name,age,eyecolor,gender,eyeglasses)
{
this.name=name;
this.age=age;
this.eyecolor=eyecolor;
this.gender=gender;
this.eyeglasses=eyeglasses;
}
var Dad=new person("Dad",45,"blue","male",true);
var Mom=new person("Mom",48,"blue","female",false);
var Brother=new person("Brother",16,"blue","male",false);
var Sister=new person("Sister",15,"green","female",false);
function askQuestion (){
}
function begin(){
askQuestion();
}
Now what I want is a way that I can, in the askQuestion function, select a question from a list based on what we know so far about the person. And then recalculate who of the people it could be, and then pick another question to ask, until we know who it is. Hopefully I've made this clear. How would I do that?
This is a bit like the game "Guess Who?" no? Alright so this is what you do:
First you create a constructor for a person. You got this right.
function Person(name, age, eyecolor, gender, eyeglasses) {
this.name = name;
this.age = age;
this.eyecolor = eyecolor;
this.gender = gender;
this.eyeglasses = eyeglasses;
}
Then you create list of possible people. A list means an array.
var people = [
new Person("Dad", 45, "blue", "male", true),
new Person("Mom", 48, "blue", "female", false),
new Person("Brother", 16, "blue", "male", false),
new Person("Sister", 15, "green", "female", false)
];
Then you keep asking questions to guess who the person is. To keep asking means to use a loop. We'll keep looping until there's only one person left in the list (the person we're looking for):
while (people.length > 1) askQuestion();
Next we define the askQuestion function. First we need to select what question to ask. So we make a list of questions. Again this is an array. We'll also store which property to test and the result for true and false conditions.
var questions = [
["eyecolor", "blue", "green", "Does the person have blue eyes?"],
["gender", "male", "female", "Is the person a male?"],
["eyeglasses", true, false, "Does the person wear eyeglasses?"]
];
These three questions are all you need to know to determine who the person is. Next we record which question is currently being asked (0, 1 or 2).
var question_no = 0;
Finally we ask the questions to determine who the person is:
function askQuestion() {
var question = questions[question_no++];
var answer = confirm(question[3]) ? question[1] : question[2];
var predicate = question[0];
people = people.filter(function (person) {
return person[predicate] === answer;
});
}
Here we ask the user a question, determine which answer he chose and use that information to filter the people who match the given description. Finally we end up with one person:
alert("The person you're thinking about is " + people[0].name + ".");
See the working demo here: http://jsfiddle.net/9g6XU/
Here's how I would do it. It's shorter than Aadit's answer, and in my opinion, simpler and easier to understand.
Make a list of the people. Use an array literal:
var people = [Dad, Mom, Brother, Sister];
I like to structure my code, so I would put the questions in an object:
var questions = {
"Are they male or female?" : 'gender',
"What is their eye color?" : 'eyecolor',
"Do they wear glasses?" : 'eyeglasses'
};
This could be expanded with as many properties as you want.
Then:
for (question in questions) { //This is how you loop through an object
var property = questions[question]; //This gets the second part of the object property, e.g. 'gender'
var answer = prompt(question);
//filter is an array method that removes items from the array when the function returns false.
//Object properties can be referenced with square brackets rather than periods. This means that it can work when the property name (such as 'gender') is saved as a string.
people = people.filter(function(person) { return person[property] == answer });
if (people.length == 1) {
alert("The person you are thinking of is " + people[0].name);
break;
}
if (people.length == 0) {
alert("There are no more people in the list :(");
break;
}
}
And I, too, made you a fiddle.Here it is.

Categories