Access object properties after they are assigned by another function - javascript

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.

Related

Am i thinking clearly here in creating a new object?

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

Calling an object in a function

I have the following code I'm working on:
function price ([arg1,arg2]) {
let city1 = {coffee:0.5, water:0.8, beer:1.2, sweets:1.45, peanuts:1.6};
let city2 = {coffee:0.4, water:0.9, beer:1.4, sweets:1.25, peanuts:1.8};
console.log (arg1[arg2]);
}
price (["city1","water"])
What I'm trying to achieve here is, have the price of a particular product be listed when you call the function with the city name and the product.
From what I can see, it's because "city1" gets input as a string, which is why I get no results when calling the function. Any ideas how I can convert the arg1 input from string to an object?
I looked into using window and eval, but I wasn't able to find a way to properly use them in this one. I know it's a dumb question, and that I'm probably missing something obvious, but I pretty much tried everything I can think of.
Just rethink how you're using the objects. By using the bracket notation rather than the dot notation for accessing object properties you are able to pass in a string, which is helpful for getting values not known beforehand. Below is an example but do note you also should check if the property actually exists as well.
Also worth mentioning is that you shouldn't pass your argument in as an array like that. Either pass them in directly or use an object.
function price (city, item) {
let cities = {
city1 : {coffee:0.5, water:0.8, beer:1.2, sweets:1.45, peanuts:1.6},
city2 : {coffee:0.4, water:0.9, beer:1.4, sweets:1.25, peanuts:1.8}
}
let res = cities[city][item]
console.log(res)
return res;
}
price ("city1", "water")
You could use the cities as key for an object and access it via a key, as well as the key for the product.
function price(city, product) {
return (data[city] || {})[product];
}
var data = { city1: { coffee: 0.5, water: 0.8, beer: 1.2, sweets: 1.45, peanuts: 1.6 }, city2: { coffee: 0.4, water: 0.9, beer: 1.4, sweets: 1.25, peanuts: 1.8 } };
console.log(price("city1", "water"));
console.log(price("foo", "bar"));

Getting first object inside JSON

I'll cut straight to the chase. I'm getting a json object with another object inside of it like so:
function getName(summonerName, region) {
LolApi.Summoner.getByName(summonerName, region, function(err, summoner) {
if(!err) {
console.log(summoner);
}
});
}
However, the result of this call is (let's stay summonerName is "tetsii"):
{ tetsii:
{ id: 51520537,
name: 'tetsii',
profileIconId: 23,
summonerLevel: 23,
revisionDate: 1408307600000
}
}
Now, I can access the id's and stuff with "console.log(summoner.tetsii.id)" for example, but because the summonerName (in this case "tetsii") can be anything, I prefer not to do it like so. So, my question is: how to access the first object inside a JSON or is there another way? And no, I can't get an array in this case afaik.
I would like to note that I've tried "console.log(summoner.summonerName.id)", but that doesn't yield results as summonerName is a string.
Thanks everybody
EDIT: Got the answer. By simply using summoner[summonerName].id I am able to grab the id. Thanks everyone for answers!
-Tetsii
By using Object.keys. For example, if you know that summoner will only have a single top-level key, you can get it with:
var summonerName = Object.keys(summoner)[0];
Obligatory browser support notice: IE < 9 does not support this out of the box, but you can use a polyfill provided in the MDN page as a compatibility shim.
There is no order in objects, so there's no guarantee you'll get the object you think, but using Object.keys and shift() you can do
var first = summoner[Object.keys(summoner).shift()];
If there is no way to return it as an array, the best idea is to iterate over the object properties as documented in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
The most important part is:
for (var prop in summoner) {
console.log("summoner." + prop + " = " + summoner[prop]);
}
Tested in console:
var summoner = { tetsii:
{ id: 51520537,
name: 'tetsii',
profileIconId: 23,
summonerLevel: 23,
revisionDate: 1408307600000
}
};
yields:
summoner.tetsii = [object Object]

Better way to build JSON array and retrieve its elements

Here's how I'm initializing and building an array:
var newCountyInfo = new Object();
newCountyInfo.name = newCountyName;
newCountyInfo.state = newCountyState;
newCountyInfo.zips = newCountyZips;
newCountyInfo.branchID = newCountyBranchID;
So I have my four elements in the array. I'm then passing newCountyInfo to another function to pull out the elements for display in some HTML elements.
The only way I know how to get to the individual elements in the function that uses them is this:
JSON.parse(JSON.stringify(newCountyValidation)).name
JSON.parse(JSON.stringify(newCountyValidation)).state
... etc...
There's got to be a better/shorter/more elegant way of doing this!
What is it?
Why are you serializing at all? I don't understand what JSON has to do with this, unless you're using web workers, ajax, or something else which demands serialization. Start with object literal syntax:
var newCountyInfo = {
name: newCountyName,
state: newCountyState,
zips: newCountyZips,
branchID: newCountyBranchID
};
And just pass the whole object to the other function:
someOtherFunction(newCountyInfo);
Which can access the fields using plain old property accesses:
function someOtherFunction(foo) {
console.log(foo.name); // whatever was in newCountyname
}
No JSON whatsoever.
Something like this should work just fine:
var newCountyInfo = {
name: newCountyName,
state: newCountyState,
zips: newCountyZips,
branchID: newCountyBranchID
}
function test(newCountyValidation)
{
alert(newCountyValidation.name);
}
test(newCountyInfo);

Assigning objects to keys inside a JavaScript object

I want to create an object like this:
var servers =
{
'local1' :
{
name: 'local1',
ip: '10.10.10.1'
},
'local2' :
{
name: 'local2',
ip: '10.10.10.2'
}
}
This is what I'm doing
$.each( servers, function( key, server )
{
servers[server.name] = server;
});
Where servers is an array of objects like these:
{
name: 'local1',
ip: '10.10.10.1'
}
But the code above does not assign any keys to the object, so the keys default to 0,1,2....
One potential bug I notice is that you're modifying the object that you are iterating over (servers). It might be good to create a new empty object that you modify in the loop.
Also, it'd help if you posted some sample data so we can run your code for ourselves.
Finally, you could try inserting a debugger keyword in there and stepping through the code.
In Chrome if You run this:
a = [];
b = {n:"c",i:"1.2.3.4"};
a[b.n] = b;
alert (a["c"].i);
alert (a.c.i);
You will got the "1.2.3.4" string as expected. But if you change the example as:
a = {};
b = {n:"c",i:"1.2.3.4"};
a[b.n] = b;
alert (a.c.i);
You will get the same "1.2.3.4" again :). So the answer is: your code assigns the properties to the objects as you asked. The only difference is that in the first example you used the array as object, and in second the simple object.
AFAIK [] in javascript is used to index arrays, while to access object properties you have to use dot notation. So your code should be:
$.each( servers, function( key, server )
{
var name = server.name;
eval("servers." + name + " = server");
});
Please try it out since I don't test it.

Categories