This question already has answers here:
Accessing Properties in object [duplicate]
(3 answers)
Closed 7 years ago.
I used to believe that there is no difference between them but after seeing this piece of code, all my information about objects in Javascript failed.
var search = function(name) {
for(var x in friends) {
if(friends[x].firstName === name) {
console.log(friends[x]);
return friends[x];
}
}
};
This code works. But
var search = function(name) {
for(var x in friends) {
if(friends.x.firstName === name) {
console.log(friends.x);
return friends.x;
}
}
};
this doesn't.
Thanks for explaining.
friends.x is not the same thing as friends[x], it's the same thing as friends['x'].
When you use friends[x] the value x can be a variable (or any expression), but when you use friends.x the x is a literal name, it won't use the variable x.
As #Guffa already explained, friends.x and friends['x'] are the same, the difference in those approaches is that when you use [] this syntax you can use variables, 'property like this', or reserved words, this is good when you do not know exactly the property you will need.
Related
This question already has answers here:
Getters \ setters for dummies
(14 answers)
Closed 5 years ago.
my so far understanding with object literal is we can use it like the key value pair, where key is the property and the value can be a actual value, a function or a anonymous function
function a() {
return 'value b';
}
var result = {
'keya': 'valueA',
'keyb': a,
'keyc': function () {
console.log('some value');
}
};
till i read this block of code
var obj = {
log: ['test'],
get latest() {
if (this.log.length == 0) return undefined;
return this.log[this.log.length - 1];
}
}
console.log(obj.latest); // Will return "test".
my question is, in the above code the function latest() doesnt have any key then how can it be used inside a object literal, am i missing something
This is ES6 (which is also called ES2015) syntax, it's a newer version of Javascript that lets you do this.
You would've had to have the key there in ES5 code.
This question already has answers here:
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Closed 7 years ago.
is it possible to get a reference to an object with the object itself
obj
and the attributes in string form
'address.town.street'
so that at the end it resolves
obj.address.town.street
i could immageine smth like the eval() function.
Try
function getValue(obj, path) {
return path.split(".").reduce(function(obj, name){ return obj[name]}, obj);
}
Do not use eval. Use this instead
Object.prototype.nestedByString=function(reference){
var current=this;
path=reference.split(".");
for(var i=0;i<path.length;i++){
current=current[path[i]];
}
return current;
}
Here is a demo
I suppose that if you're allergic to extending native prototypes, you can do this
function nestedByString(obj,reference){
var current=obj;
path=reference.split(".");
for(var i=0;i<path.length;i++){
current=current[path[i]];
}
return current;
}
This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
Closed 7 years ago.
Does anyone know a clean way to find out if an object property exists? Here is my example:
var test = {
a : 'west',
b : {
a : 'rest'
},
d : {
a : 'pest'
}
};
// I want to access 'a' in 'c'
typeof test.c.a; // fails!
typeof it seems can't get past the fact that 'c' doesn't exist to check if 'a' exists inside it (I've also tried jQuery.type() which also fails in the same way - I would have thought it would have error checking inside that function).
In this example of course I could simply check if 'c' exists first but in my real situation I have a large and deep object and I need to dynamically retrieve data from any potential location so it would be nice if there were a ready-made solution which didn't necessitate having to use a try-catch.
Thanks in advance!
I can't vouch for any existing functionality in any js framework for finding nested properties, but you can certainly roll your own.
hasOwnProperty is part of the ECMA script standard.
if(test.hasOwnProperty("c"))
{
console.log("test.c = " + test.c);
}
If you are looking to find deeply nested properties, then you could roll your own function to check if the nested property exists, and if so, return it.
function hasNestedProperty(testObject, properties)
{
var maxDepth = properties.length;
var i, hasProperty = false;
var currObj = testObject;
while(hasProperty && i < maxDepth)
{
if(currObj.hasOwnProperty(properties[i])
{
currObj = currObj[properties[i]]);
i ++;
}
else
{
hasProperty = false;
}
}
return hasProperty;
}
This question already has answers here:
Best way to find if an item is in a JavaScript array? [duplicate]
(8 answers)
How can I check if an object is an array? [duplicate]
(51 answers)
Closed 7 years ago.
I am learning JavaScript and i came across this problem. I want to catch an input value using document.formName.elementName.valueand compare that value with an instance of an Array object.If the value exists it will throw an alert!.
You can use the indexOf() function you simply do this :
array.indexOf("string")
It will return -1 if the item is not found, otherwise just the position.
Here's a link W3Schools.
I think that has been asked thousands of times:
if(myFancyArray.indexOf(document.formName.elementName.value) !== -1){
alert("You did something wrong!");
}
Watch out as old versions of IE don’t know indexOf. (but who needs IE?)
Use indexOf
function search(arr,obj) {
return (arr.indexOf(obj) != -1);
}
Test cases:
search(["a","b"], "a"); // true
search(["a","b"], "c"); //false
You can add a convenience method to JavaScript's Array
Array.prototype.includes = function(element) {
var found = false;
for (var i = 0; i < this.length; i++) {
if (this[i] == element) {
found = true;
}
}
return found;
}
And, then, you can use below code to get some syntactic sugar
var myArray = [0,1,"hello","world"];
console.log(myArray.includes("hello")); //prints true
console.log(myArray.includes(10)); //prints false
This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 7 months ago.
In PHP I can mess around with variable variables and I'm wondering if I can do the same in JavaScript.
I want to create a new object with a property which's name is based on the value of a variable.
if ( obj.name === 'foo' ) {
var data = { foo: value };
}
if ( obj.name === 'bar' ) {
var data = { bar: value };
}
Is there a shorter way of doing this without using eval()? Something like:
var data = { obj.name: value };
Try this:
var data = {};
data[obj.name] = value;
You can read some more about js objects Here.
Objects in JavaScript are simply hash maps. You can access members by indexing with their names. For your problem you can use
var data = {};
data[obj.name] = value;
I've used this to implement a dynamic dispatch mechanism for arithmetic operations on different numerical types as described here.