Difference in Javascript arrays? [duplicate] - javascript

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
JavaScript arrays braces vs brackets
I have a simple question that I can't find an answer to with Google.
What is the difference between
var foo = { };
and
var bar = [ ];
An example would help.

foo = {} is not an array, but an object (created using object literals, {}).
bar = [] is an array, which inherit various methods from the Array constructor. An array also has various properties, such as .length.
EDIT (regarding comment):
The a property of an object can be accessed through foo.a or foo["a"].
Looping through the properties of the object should be done using a for( .. in .. ) loop.
var foo = {"a":true, "b":false};
for(var prop_name in foo){
alert(prop_name + " - " + foo[prop_name]);
}
This code will show two alert messages:
a - true
b - false

Related

Reference nested json object property by string [duplicate]

This question already has answers here:
Access object child properties using a dot notation string [duplicate]
(13 answers)
Closed 3 years ago.
I know I'm missing something obvious here but say I have a JSON object that looks like this:
testObj = {
levelOne: {
levelTwo: []
}
}
I also have a string value:
var prop = 'levelOne.levelTwo';
I'm trying to determine if there's any way to basically do something like this:
var x = testObj[prop];
That doesn't work, but is there any way to do the equivalent?
There's no trivial way (e.g. testObj[prop]) of doing this, but the reduce function is well suited:
let nestedProp = (obj, path) =>
path.split('.').reduce((obj, prop) => obj[prop], obj);
let x = nestedProp({levelOne: {levelTwo: [5]}}, 'levelOne.levelTwo');
console.log(x);
You can use dynamic keys to access properties in an object but not multiple levels down.
i.e. You can do const a = testObject["levelOne"] but not what you tried. (Docs)
There are however helper libs that have functions to do this. One example is lodash.get function

Get from JSON object with string IDs to JS numeric IDs [duplicate]

This question already has answers here:
Is there any way to use a numeric type as an object key?
(11 answers)
Closed 4 years ago.
i have a JSON object (sent from php) and I want to convert the IDs to a numeric key using JS. So currently it looks something like that:
let foo = {"66":"test","65":"footest"};
And now I want it to look like this:
let foo = {66:"test",65:"footest"};
Object keys do not need to be numerical to be accessed - as noted in the comments - they are strings regardless.- Below, I am console logging the "66" property using the brackets notation - foo[66]
let foo = {"66":"test","65":"footest"};
console.log(foo[66]); // gives "test"
// if you want to assign values numerically - ie using the index of a loop - then you could do
for(i = 63; i<65; i++) {
foo[i] = "test" + i;
}
console.log(foo); // gives {"63": "test63", "64": "test64","65": "footest","66": "test"}

Understanding Object.keys in javascript [duplicate]

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 8 years ago.
I have a following object:
var sample =
{
count: {
'20-01-2015/17': {
'a': 553056,
'b': 622123
},
'20-01-2015/18': {
'a': 519008,
'b': 610474
}
}
}
I want to find all the keys for count property. Also, all the keys for 20-01-2015/17 property also.
var times = Object.keys(sample.count);
console.log(times);
var time = '20-01-2015/17'
//This works
var props = Object.keys(sample.count[time]);
console.log(props);
//But this doesn't work. I am not able to understand that.
props = Object.keys(sample.count.time);
console(props)
I didn't understand why the first approach is working, but not the second one.
Object.keys() is used to ENUMERATE all properties that have their Enumerable flag turned on in the object descriptor including functions, for example, if you do this Objects.keys(Array.prototype) it will print all the functions defined on the prototype property of the Array which is shared by all Array objects.

Javascript : Check if object has properties [duplicate]

This question already has answers here:
if (key in object) or if(object.hasOwnProperty(key)
(9 answers)
Closed 8 years ago.
There are several answers here how to check if a property exists in an object.
I was always using
if(myObj.hasOwnProperty('propName'))
but I wonder if there is any difference from
if('propName' in myObj){
They are almost equal, the difference is that hasOwnProperty does not check down the prototype chain, while in does.
An example
var test = function() {}
test.prototype.newProp = function() {}
var instance = new test();
instance.hasOwnProperty('newProp'); // false
'newProp' in instance // true
FIDDLE
As noted, Object.hasOwnProperty only returns "own properties", i.e. properties that are added directly, and not properties added to the prototype.
Yes, there is difference. hasOwnProperty() ignores properties and methods which are added with prototype. I try to explain with examples. For instance if you have prototype of object
Object.prototype.something = function() {};
And let's say you have following object
var obj = {
"a" : "one",
"b" : "two"
};
And loop:
for ( var i in obj ) {
//if (obj.hasOwnProperty(i)) {
console.log(obj[i]);
//}
}
Without hasOwnProperty it will output one two function(), while with hasOwnProperty() method only one two
See the differences between First and Second DEMOS

Define Javascript object using dynamic string literal as object propery name [duplicate]

This question already has answers here:
Is it possible to add dynamically named properties to JavaScript object?
(20 answers)
Closed 3 years ago.
Needing to do:
var some = {
`${foo1}_${foo2}`: bar
}
but this gives a syntax error though I must do it somehow. How?
you can suppose object as hashmap and access properties via []
var foo1 = 'a';
var foo2 = 'b';
var some = {};
some[foo1+'_'+foo2] = 'test';
console.log(some.a_b);

Categories