How to access this, is this an object literal or? - javascript

My javascript looks like:
[{"user":{"property1":8,"property2":"asdfasdf"}}];
I tried:
alert(user.property1);
But nothing rendered, what am I missing here?

Your javascript is an array, I assume it's assigned to a variable?
var myArray = [{"user":{"property1":8,"property2":"asdfasdf"}}];
alert(myArray[0].user.property1);

You don't seem to assign the object literal to a variable. You must do that in order to be able to reference it the way you seem to want. Note that [] indicates an array.
So you're almost there:
var myObj = [{"user":{"property1":8,"property2":"asdfasdf"}}];
alert(myObj[0].user.property1);
Your object literal creates an array, with an object that has a property named user. This user property itself is set to an object which has two properties - property1 and property2.

Related

JavaScript Conceptual Issue with a code. Please give an explanation for the output i am getting

I am having difficulty in understanding the following code, i have put a comment where i do not understand the concept, what exactly is going on
var ob = {};
var ob2 = ['name'];
for(var op of ob2)
{
ob[op]='at'; // here i dont understand what is happening, why here is an array type brackets
}
console.log(ob);
OUTPUT IS
name:'at'
That is just the syntax for accessing or assigning properties of an object dynamically in javascript.
You can think of it as though you are doing: ob.name = 'at'.
There are two ways to access object properties in JavaScript
var person = {
name: 'Jane'
}
person.name
// or
person['name']
// both return jane
in your case, that iterates through members of the array called ob2
first and only element of that array is a string name and it's given to that object as a prop, which becomes like following
ob['name'] = 'at';
// or
ob.name = 'at';
When to use brackets([]) over dot(.)
If you don't know the prop name at runtime you need to go with brackets, if you do know it you can choose either dot notation or brackets
Basically, it's accessing a property of the object ob. In this case, is accessing and creating new properties.
The loop is getting each index value, and for each assign/create a new property using that index value.
That approach is a dynamically way of creating property-names in an object.
ob['name'] = 'at';
ob.name = 'at'; // Just to illustrate
Read a little the docs here -> JavaScript object basics - Learn web development | MDN

Variable by id and class type

How to know the type of variable containing the result of document.getElementById()?
For example, on using alert(typeof variable), I get object but we refer these variables like array in document.getElementsByClassName[i].
I want to know what exactly is the type of the variable containing the value and how are we using it as an array.
var cv = document.getElementById("xyz");
alert(typeof cv); //Alerts object
But we use these variables as arrays like..
var cv = document.getElementsByClassName("xyz");
cv[0].style.height="200px"; //use as array
On evaluating it further using array.isarray(),it turns out that it is not an array..So how are we able to use the variable as an array like in the code written "use as array"?
Welcome to Stack Overflow.
typeof returns object for both arrays and objects, all it means is that it is a non-primitive data type.
If you are interested in determining if it is an array, you can use Array.isArray() like this
const values = [1,2,3]
if (Array.isArray(values))
console.log("It's an array")
Notice that I used console.log instead of alert(), if you have many of them it doesn't hold up the execution.
document.getElementById gives you a reference to a single DOM Element object
document.getElementsByClassName gives you an array-like object, which is a live HTMLCollection of found elements

Does object literal return a newly created object?

I was learning about object literal syntax {}. I learnt that an object can either be created like
var person = {};
person.name = "myName"
or like
var person = {firstname: "myName"}
Now i wanted to pass this object into a function, and so i learnt that objects can also be created on the fly like
sayHelloTo({firstname: "myName"})
Finally, I typed {} in console, and it showed - `Object().
Does this mean than {} is actually a function or something that is actually returning a newly created object, which then gets stored in the variable? Is it a function or something else? Is it same as var person = new Object() ?
The object literal syntax does create a new object but it is not a function. If anything, it's more akin to an operator.
While the spec does have a whole category of literals (11.8), the object literal is not part of that section. Instead, it's defined later under 12.2.6 (object initializer). As the leading note states:
An object initializer is an expression describing the initialization of an Object, written in a form resembling a literal.
(emphasis mine)

Why can't we directly set array values in javascript?

I have an empty object myscroll defined as var myscroll = {}. Now I want to add an array property to it. I did it as follows:
var myscroll = {}
myscroll.point[0] = getScrollpos("home");
myscroll.point[1] = getScrollpos("artists");
myscroll.point[2] = getScrollpos("songs");
myscroll.point[3] = getScrollpos("beats");
myscroll.point[4] = getScrollpos("contact");
I get the error myscroll.point is not defined. Then I first defined it as myscroll.point = [];, then the code worked.
So, Why can't we directly set array values and add that property to an object in javascript? Why do we have to define it first independently?
When you are dealing with object properties, by default you can access any object property and value of that property would be undefined if it wasn't set before. So, by accessing not defined property with index (myscroll.point[0]) you are trying to access property 0 of undefined, which is primitive value in javascript and has no properties, so you are getting TypeError.
As result you can set primitive values to not defined object property, but cannot dial with not defined prop as with object.
Also wanna to point you and explain situation with a little bit similar from first view situations in code below:
var obj = []
obj[0] = 10
notDefinedObj[0] = 10 // cause ReferenceError
Array is object. In JS you can't modify/add/delete object properties without initialising object before.
That's caused because objects are stored in memory and you can access them by reference. When you attempt to add new property to it, for instance add new element to list, you are trying to attach property to variable which has no Reference, that's why you are getting ReferenceError.
Good Luck!
With myscroll.point you're trying to access a point property on the myscroll object. But there is no such property on that object. That's why you're getting a undefined is not an object error message (or something similar - depending on your browser).
If you're coming from PHP, this might be strange but actually it's much more explicit than the magic involved in the following php snippet for example:
$myscroll = [];
$myscroll['point'][0] = getScrollpos("home");
// ...
PHP automagically created sub arrays for keys that do not exist.
Update after comment
There is a significant difference between myscroll.mypoint = 5; and myscroll.point[0] = getScrollpos("home");.
In the first case your setting the point property on myscroll to 5 explicitly. But in the second case you're trying to access the [] operator (which is an array operator) on a non-existing property point. Theoretically Javascript could do the same magic as PHP and create the array automagically on the fly, but it doesn't. That's why your getting an error.
It's the same as trying to access a fictitious property myproperty on myscroll.mypoint like myscroll.mypoint.myproperty. This will not work as well, because you're trying to access myproperty on mypoint which is undefined on myscroll.
Because myscroll.point[0] = getScrollpos("home"); can be understood as Get the first element of the point array inside of myscroll and set it to... You can't access the first element of an non-existing array.
Simply check typeof of myscroll array variable and then check the typeof of myscroll.point. You have tried to assign properties of an array, outside of an array. It is empty or undefined.
You are trying to access the point property of myscroll which is not defined (because myscroll = {}).
If you will look at the console with myscroll.point, it will return you undefined. Here you were trying to put something in undefined so you got TypeError: myscroll.point is undefined.
If you define myscroll like this:
var myscroll = {
point : []
}
Then your code will work and you won't need to define myscroll.point = [].
if you have an an empty object and you want to set a new property that holds an array you should do this.
var obj = {};
obj['propertyName'] = [];
this will put a property with corresponding propertyName that holds an array that you can later populate.
if your getScrolloops() returns an array you can do this
obj['propertyName'] = getScrolloops();
Idealy in your case you can do this:
obj['propertyName'] = [getScrollpos("home"),
getScrollpos("atrist"),
getScrollpos("songs"),
getScrollpos("beats"),
getScrollpos("contact")
];
EDIT: Explanation: Why is your code not working?
As explained here:
You can define a property by assigning it a value.
What you do is trying to define a property by assigning a value to an index of that property. This will not work because you are not assigning a value to the property it's self but to index of a property that dose not exist.
Also i need to mention that you can use both property accessors to achieve that. This could be a helpful link.

Elements in Javascript object coming out undefined

To construct an object like this:
params (Object) (defaults to: {}) —
Delete — required — (map)
Objects — required — (Array<map>)
Key — required — (String) Key name of the object to delete.
I'm doing this:
var params = {
Bucket : data.bucket,
Delete: [{
Objects:[{ Key:""}] }]
};
for(i=0;i<data.keys.length;i++){
params.Delete[0].Objects[i].Key = data.keys[i];
}
It breaks on the Key with
params.Delete[0].Objects[i].Key = data.keys[i];
^
TypeError: Cannot set property 'Key' of undefined
What am I doing wrong?
It turns out there is only one Key inside of Objects. I'd like to put as many keys as I want inside of Objects so as to properly construct the object. How can I do this?
How many object literals are in the Objects array? From your initialization it only looks like 1. But you are using a for loop, implying you expect more than one.
That error means Objects[i] is undefined for whatever value of i you reach when it occurs.
It seems like you need to do something like
for(i=0;i<data.keys.length;i++){
params.Delete[0].Objects.push({Key: data.keys[i]})
}
to get new object literals into your Objects array as you process your data (change your definition of params to just have an empty array for Objects initially).
Your params.Delete[0].Objects here has only one object in it and it happens when the i is 1. you are counting a for loop based on the other loop with 2 different length.
data.keys
is different from:
params.Delete[0].Objects
this one has only one object, whereas the first one has more than one object.

Categories

Resources