What does assigning a variable to {}, mean? Is that initializing it to a function? I have code in a javascript file that says this
GLGE.Wavefront = function(uid) {
GLGE.Assets.registerAsset(this,uid);
this.multimaterials = [];
this.materials = {}; // <---
this.instances = [];
this.renderCaches = [];
this.queue = [];
};
how is that assignment different from an array? Is it a type of array?
What does assigning a variable to {}, mean?
It is an object literal (with no properties of its own).
Is that initializing it to a function?
No, that would be = function () { }.
how is that assignment different from an array?
An array has a bunch of features not found in a basic object, such as .length and a bundle of methods.
Objects are often used to store arbitrary key/value pairs. Arrays are for ordered values.
This is javascript object notation. Particularly {} means empty object, the same as new Object();. See json.org.
That would be an empty JavaScript object.
Using {} creates an object. You can use the object like a hash-map or similar to how you can use arrays in PHP.
var obj = {};
obj['test'] = 'valuehere';
obj.secondWay = 'secondValue';
and you could access them by calling obj.test and obj['secondWay'].
It's an initialized empty object, eg. an object of no particular type. It serves to provide a definition for this.materials so that the code won't have to check it for null or being defined later.
It does create an empty object.
var myObj = {};
Within an object you can define key/value pairs, e.g.:
myObj.color = 'red';
A value can be a function, too:
myObj.getColor = function() { return this.color };
It's JON (Javascript Object Notation) for creating a new empty object. Almost equal in idea to how you'd normally do Object x = new Object() in java, minus the initialization part...
Related
Couldn’t understand the difference between object and plain object in JavaScript.
I know how Object looks like but don’t understand plain object. I googled about this but couldn’t understand.
As per my understanding normal object looks like below
const object = {};
Or we do call functions as objects in JavaScript
function test() {
}
But what is plain object? how it differs with normal object. Thank you
Edit:
My confusion started about plain object after looking at below error. So my query is to understand the concept of plain object in JavaScript
Actions must be plain objects. Use custom middleware for async actions.
I think you wanted to mean Plain Old JavaScript Object as plain object.
In vanilla JavaScript a POJO (Plain Old JavaScript Object) is the simplest kind of object you could possibly have: a set of key-value pairs, created by the {} object literal notation or constructed with new Object().
Plain Old JavaScript Object:
Using the bracket's syntactic sugar also known as object literal:
var obj = {};
Using the Object() constructor:
var obj = new Object();
Other Than Plain Object:
Using a function constructor:
var Obj = function(name) {
this.name = name;
}
var c = new Obj("hello");
Using ES6 class syntax:
class myObject {
constructor(name) {
this.name = name;
}
}
var e = new myObject("hello");
Plain object(POJO - Plain Old Javascript Object)
var plainObj1 = {}; // typeof plainObj1 --> Object
var plainObj2 = {name : "myName"}; // typeof plainObj2 --> Object
var plainObj3 = new Object(); // typeof plainObj3 --> Object
Non Plain object
var Person = function(){}; //class
var nonPlainObj = new Person(); // typeof nonPlainObj --> function
An Object created by literal notation or new Object are know as plain object. example :
let a = {aaa : 1}
let b = new Object()
while Object created using function are not plain object
let C = function(){}
let d = new C()
You are talking about object literals, which is a literal object, {}. Like array literals use [] instead of new Array(). This is an object whose prototype is Object. A string is an Object too, but its prototype chain looks like: String -> Object. Arrays are Array -> Object. These are all objects.
An object literal's prototype is just, well, Object.
Any object created with object literals notation is called plain Objects in JavaScript
function Animal(){
//Some codes
}
var obj = new Animal();
In your question, you cite that you think both an object literal and a function are both "objects". In JS, function is a type, and so is object. So your original question, those two items are not objects ...
plain objects (sets of key/value pairs wrapped in { } ) are great for storing simple data sets.
var lunch={
sandwich:'furkey',
drink:'soda',
chips:true
}
like in react redux actions are written in key/value pairs.
hope you understand it.
This question already has answers here:
Get property of object in JavaScript
(3 answers)
Closed 6 years ago.
I am trying to access a property within an object and return it.
Note the name of the object can change, so accessing it using title_can_change.property will not work.
Take the following object:
{
"title_can_change":{
property: 1
}
}
How do I return the value of 'property'?
MORE INFO:
This object is being returned from a search which contains an array of results from several API's. This object is returned to detail the API the result has come from (the search goes through several API's).
So this would be more like:
apiData:{
"apiName":{
price: 500
}
}
"apiName" is not fixed and changes to say the name of the API. So it cannot be referenced by "apiName' in any of the code.
You could create a function to return the value of the property of whatever object you pass to it:
var getProperty = function(obj) {
return obj.property;
};
If you have an object and you want to access it's first key's value you can go with something like this (dirty example):
var myObj = {
"title_can_change"{
property: 1
}
}
myObj[Object.keys(myObj)[0]];
I home this helps.
So I think I know what you are wanting and here is a low-level solution that may prove valuable and show you some neat things about the language.
https://jsfiddle.net/s10pg3sh/1/
function CLASS(property) {
// Set the property on the class
this.property = property || null;
}
// Add a getter for that property to the prototype
CLASS.prototype.getProperty = function() {
return this['property'];
}
var obj = new CLASS(9);
alert(obj.getProperty());
What you are doing in the above is creating a "class" for your new variable. When you create your object with the new keyword as show you still get your normal JS object (everything is an object anyways), but you get the convenience of the getProperty method. This being on the prototype insures that any new CLASS variables you create will have that method. You can change the variable names and you will always have access to that property by having access to the instance (variable). This is a very common OO paradigm and is the strength of a prototypical language so while it may be over the top for your needs I figured I would add it as an answer here...
If this object is global, then you can use window['title_can_change']['property']. If it's just another property of another object (called another_one) you can access it with another_one['title_can_change']['property'].
Furthermore: You can have a variable (let's call it title_name) to ease the call:
....
var title_name = "title_can_change";
var myObj = window[title_name]['property'];
title_name = "title_has_changed";
var anotherObj = window[title_name]['property'];
.....
OR
....
var title_name = "title_can_change";
var myObj = another_one[title_name]['property'];
title_name = "title_has_changed";
var anotherObj = another_one[title_name]['property'];
.....
Kind of a guess here since the question is still somewhat unclear. I am assuming that you want to iterate over an objects properties whose names are unknown.
This might be a solution.
for (var property in object) {
if (object.hasOwnProperty(property)) {
// check objects properties for existence
// do whatever you want to do
}
}
Use for...in to iterate over the keys of the object and check if your inner object contains your property
var o = {
"title_can_change":{
property: 1
}
};
for (var k in o) {
if (o.hasOwnProperty(k) && o[k].property) {
return o[k].property;
}
}
What’s the difference between “{}” and “[]” while declaring a JavaScript array?
Normally I declare like
var a=[];
What is the meaning of declaring the array as var a={}
Nobody seems to be explaining the difference between an array and an object.
[] is declaring an array.
{} is declaring an object.
An array has all the features of an object with additional features (you can think of an array like a sub-class of an object) where additional methods and capabilities are added in the Array sub-class. In fact, typeof [] === "object" to further show you that an array is an object.
The additional features consist of a magic .length property that keeps track of the number of items in the array and a whole slew of methods for operating on the array such as .push(), .pop(), .slice(), .splice(), etc... You can see a list of array methods here.
An object gives you the ability to associate a property name with a value as in:
var x = {};
x.foo = 3;
x["whatever"] = 10;
console.log(x.foo); // shows 3
console.log(x.whatever); // shows 10
Object properties can be accessed either via the x.foo syntax or via the array-like syntax x["foo"]. The advantage of the latter syntax is that you can use a variable as the property name like x[myvar] and using the latter syntax, you can use property names that contain characters that Javascript won't allow in the x.foo syntax.
A property name can be any string value.
An array is an object so it has all the same capabilities of an object plus a bunch of additional features for managing an ordered, sequential list of numbered indexes starting from 0 and going up to some length. Arrays are typically used for an ordered list of items that are accessed by numerical index. And, because the array is ordered, there are lots of useful features to manage the order of the list .sort() or to add or remove things from the list.
When you declare
var a=[];
you are declaring a empty array.
But when you are declaring
var a={};
you are declaring a Object .
Although Array is also Object in Javascript but it is numeric key paired values.
Which have all the functionality of object but Added some few method of Array like Push,Splice,Length and so on.
So if you want Some values where you need to use numeric keys use Array.
else use object.
you can Create object like:
var a={name:"abc",age:"14"};
And can access values like
console.log(a.name);
var a = [];
it is use for brackets for an array of simple values.
eg.
var name=["a","b","c"]
var a={}
is use for value arrays and objects/properties also.
eg.
var programmer = { 'name':'special', 'url':'www.google.com'}
It can be understood like this:
var a= []; //creates a new empty array
var a= {}; //creates a new empty object
You can also understand that
var a = {}; is equivalent to var a= new Object();
Note:
You can use Arrays when you are bothered about the order of elements(of same type) in your collection else you can use objects. In objects the order is not guaranteed.
they are two different things..
[] is declaring an Array:
given, a list of elements held by numeric index.
{} is declaring a new object:
given, an object with fields with Names and type+value,
some like to think of it as "Associative Array".
but are not arrays, in their representation.
You can read more # This Article
Syntax of JSON
object = {} | { members }
members = pair | pair, members
pair = string : value
array = [] | [ elements ]
elements = value | value elements
value =
string|number|object|array|true|false|null
In JavaScript Arrays and Objects are actually very similar, although on the outside they can look a bit different.
For an array:
var array = [];
array[0] = "hello";
array[1] = 5498;
array[536] = new Date();
As you can see arrays in JavaScript can be sparse (valid indicies don't have to be consecutive) and they can contain any type of variable! That's pretty convenient.
But as we all know JavaScript is strange, so here are some weird bits:
array["0"] === "hello"; // This is true
array["hi"]; // undefined
array["hi"] = "weird"; // works but does not save any data to array
array["hi"]; // still undefined!
This is because everything in JavaScript is an Object (which is why you can also create an array using new Array()). As a result every index in an array is turned into a string and then stored in an object, so an array is just an object that doesn't allow anyone to store anything with a key that isn't a positive integer.
So what are Objects?
Objects in JavaScript are just like arrays but the "index" can be any string.
var object = {};
object[0] = "hello"; // OK
object["hi"] = "not weird"; // OK
You can even opt to not use the square brackets when working with objects!
console.log(object.hi); // Prints 'not weird'
object.hi = "overwriting 'not weird'";
You can go even further and define objects like so:
var newObject = {
a: 2,
};
newObject.a === 2; // true
[ ] - this is used whenever we are declaring an empty array,
{ } - this is used whenever we declare an empty object
typeof([ ]) //object
typeof({ }) //object
but if your run
[ ].constructor.name //Array
so from this, you will understand it is an array here Array is the name of the base class.
The JavaScript Array class is a global object that is used in the construction of arrays which are high-level, list-like objects.
What is the JavaScript equivalent function for CreateObject("Scripting.Dictionary")?
I have to convert following two statements from VBScript to JavaScript, anyone can help me to find a solution.
Set oInvoicesToCreate = CreateObject("Scripting.Dictionary")
If Not oInvoicesToCreate.Exists(cInvoiceID) Then
oInvoicesToCreate(CStr(cInvoiceID)) = ""
End If
var oInvoicesToCreate = {};
if(oInvoicesToCreate[cInvoiceID] === undefined){
oInvoicesToCreate[cInvoiceID] = "";
}
You probably don't want to check the hasOwnProperty method because you'll want to check if anything in the prototype chain has that property as well and not overwrite it. checking with the []s will let you know if any property on any prototype items have the property as well.
As bluetoft says in this answer, in Javascript you can use a plain object instead. However, there are a few differences between them that you should be aware of:
First, a Dictionary's keys can be any type:
var dict = new ActiveXObject('Scripting.Dictionary');
dict(5) = 'Athens';
console.log(dict('5')); //prints undefined
whereas any value used for a Javascript object's key will be converted to a string first:
var obj = {};
obj[5] = 'Athens';
console.log(obj['5']); // prints 'Athens'
From MDN:
Please note that all keys in the square bracket notation are converted to String type, since objects in JavaScript can only have String type as key type. For example, in the above code, when the key obj is added to the myObj, JavaScript will call the obj.toString() method, and use this result string as the new key.
Second, it is possible to set a Dictionary to treat differently cased keys as the same key, using the CompareMode property:
var dict = new ActiveXObject('Scripting.Dictionary');
dict.CompareMode = 1;
dict('a') = 'Athens';
console.log(dict('A')); // prints 'Athens'
Javascript key access via [] doesn't support this, and if you want to treat differently-cased keys as the same, you'll have to convert the potential key to lowercase or uppercase before each read or write.
For your specific scenario, neither of these differences matter, because the keys are numeric strings (1) which have no case (2).
Convert this:
{"items":[{"id":"BLE89-A0-123-384","weight":"100","quantity":3},
...
{"id":"BLE10-A0-123-321","weight":"100","quantity":4}],
"country":"JUS",
"region":"A",
...
"timeout":"FILLER"}
To this:
{"BLE89-A0-123-384": "3", "BLE10-A0-123-321": "4"} that is... {id: quantity}
I found an answer that almost does what I need: Searching for an Object inside the JSON. But that answer doesn't help me because it's only at the first level (one json object). My problem is at the second level (json object within a json object). Thanks in advance!
It helps if you don't think of JSON objects as JSON objects. Once you run a JSON string through JSON.parse, it is a native JavaScript object.
In JavaScript, there are two ways to access objects.
Dot Notation
The dot notation goes like this
myObject.name
See the dot? You can use that to access any object property (which indeed may be another object in javascript, as long as it has a valid dot notation name). You can't use characters like -, ., and the space character.
Bracket Notation (may be another name)
myObject["variableName"]
Like dot notation but allows some other characters, like - and the space character.. Does exactly the same thing.
Using these notations is useful because we can access nested properties.
myObj.foo.bar.baz()
Now let's get to your JSON object...
{"items":[{"id":"BLE89-A0-123-384","weight":"100","quantity":3,"stock":0},
{"id":"BLE10-A0-123-321","weight":"100","quantity":4,"stock":0}],
You might want to brush up on the JSON format yourself, but in your example, here's a few clues...
{ Means the start of an object. (Keep in mind your entire JSON string is an object itself.)
} Means the end of an object.
"variable" (with quotes! important in JSON, but not when accessing/declaring javascript objects) assigns a property to your object.
: Is the assignment operator in both JSON and JavaScript objects.
Anything to the right of the : is the value you are assigning to the property on the left.
, Means you are starting a new property within an object.
You probably know that [] with , commas inside means an array.
When we run your string through JSON.parse(string), we'll get an object that looks like this...
var myResponse = JSON.parse(response);
You can now use it as a native JavaScript object. What you're looking for is a nested property within "items".
var items = myResponse.items; //alternatively you could just use myResponse.items
Since items is an array of objects, we'll need to iterate through it in order to convert the existing object into a new object.
var i;
var result = {} ; //declare a new object.
for (i = 0; i < items.length; i++) {
var objectInResponse = items[i]; //get current object
var id = objectInResponse.id; //extract the id.
var quantity = objectInResponse.quantity;
result[id] = quantity; //use bracket notation to assign "BLE89-A0-123-384"
//instead of id. Bracket notation allows you to use the value
// of a variable for the property name.
Result is now an object that looks like:
{
"BLE89-A0-123-384" : 3, //additional properties designated by comma
"BLE10-A0-123-321" : 4 // The last key/value in an object literal CANNOT
// have a comma after it!
}
You can access the properties using bracket notation.
var BLE89 = result["BLE10-A0-123-321"]; //use quotes, otherwise JavaScript will try to look up the value of a variable.
You can try with:
var obj = {
"items":[
{"id":"BLE89-A0-123-384","weight":"100","quantity":3},
{"id":"BLE10-A0-123-321","weight":"100","quantity":4}
],
"country":"JUS",
"region":"A",
"timeout":"FILLER"
};
var quantities = {};
obj.items.forEach(function (item) {
quantities[item.id] = item.quantity;
});
quantities will then be the object {"BLE89-A0-123-384":3,"BLE10-A0-123-321":4}. forEach is a native method of array objects in JavaScript that lets you iterate through their elements. You may want to put that piece of code inside a function:
function getQuantities(obj) {
var quantities = {};
obj.items.forEach(function (item) {
quantities[item.id] = item.quantity;
});
return quantities;
}
You need to do the following:
var newJSON = {};
for (var i = 0; i < oldJSON.items.length; i++) {
newJSON[oldJSON.items[i].id] = oldJSON.items[i].quantity;
}