Why is this javascript object code not working? - javascript

var house = new Object(floors: "4", color:"red", windows:"lots", bathrooms:"3");
var result ="";
for (var i in house)
{
result +="house." + i + " is " + house.i + ".<br />";
}
document.body.innerHTML += result;
I want to output house.floors is 4.<br />house.color is red.<br />and so on.

The Object constructor doesn't work like that. Use an object literal instead.
var house = { floors: "4", color:"red", windows:"lots", bathrooms:"3" }
Additionally house.i will reference the i property, not the property with the name that is stored in the string i, you want house[i].

Curly brackets:
var house = {floors: "4", color:"red", windows:"lots", bathrooms:"3"};
There's rarely a need (in fact I can't think of a reason) to use an explicit Object constructor call; just use {} for a new, plain, empty Object instance, and [] for a new, plain, empty Array instance. For objects with initial properties, use the "name:value" syntax like you did (except in curly brackets).

Related

Declare object from string

I want to declare 1 javascript object which its properties are generated from one sequence that was created earlier
example:
var x = '"property1": "abc",
"property2": "def",
"property3": "xyz",
';
var obj = {
// insert content of x here
}
what can i do?
You can declare
var x = {property1: "abc",
property2: "def",
property3: "xyz"};
var obj = {
data:x
}
Assuming you have a string that is a valid sequence of key/value pairs that are double-quoted then you can easily make it into JSON by concatenating '{' and '}', after removing any trailing comma (I notice your last property has a trailing comma). Then you can create an object by parsing that JSON. So:
var x = // Your string of quoted, comma-separated key/value pairs here
var obj = JSON.parse('{' + x.replace(/,\s+$/,'') + '}');
General note of disapproval: I don't know why you would create your properties as a string rather than just adding properties directly to an object, and in general you shouldn't hand-create JSON, and I'd like to note that a string literal enclosed by single-quotes can't have line-breaks in it so I'm hoping you just showed it that way for ease of reading.
Use JSON string here
var x = `{"property1": "abc",
"property2": "def",
"property3": "xyz"
}`;
var obj = JSON.parse(x)
After reading your comments OP I think you may be after bracket notation.
You can access an object's property via dot notation
obj.prop = foo;
var v = obj.prop;
Or you can use bracket notation
var propName = "prop"
obj[propName] = foo;
var v = obj[propName];
Note this is not accessing an array.
So you could do it this way
var data = [["property1", "abc"],["property2","def"],["property3","xyz"]]
var obj = {};
data.forEach(pk => { obj[pk[0]] = pk[1]; });
console.log(obj.property1); // output "abc"
You can use the eval API to parse the string too.
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
The eval() function evaluates JavaScript code represented as a string.
Example:
let y = "";
let x = ' "property1": "abc", "property2": "def", "property3": "xyz" ';
eval('y={' + x + '}');
Output:
Please note that using eval can be dangerous as noted in its documentation:
eval() is a dangerous function, which executes the code it's passed
with the privileges of the caller. If you run eval() with a string
that could be affected by a malicious party, you may end up running
malicious code on the user's machine with the permissions of your
webpage / extension.
Example: exposing it as a REST service to allow end-users to hit it with any 'object string' which can instead be a piece of malicious code - like downloading virus.

What do curly brackets mean in a variable declaration?

What do curly brackets ({}) do in variable declarations, when surrounding multiple pairs of the form integer:string?
For example, what do they mean here?
char = {0:'(',3:') ',6:' - '};
In this case, it's from the following phone number formatting script:
function formatPhone(obj) {
var numbers = obj.value.replace(/\D/g, ''),
char = {0:'(',3:') ',6:' - '};
obj.value = '';
for (var i = 0; i < numbers.length; i++) {
obj.value += (char[i]||'') + numbers[i];
}
}
I believe that the line defining char is the one that's causing it to fail.
This is a Javascript object. Better indented, it would look like this:
char = {
0: '(',
3: ') ',
6: ' - '
}
It's saying that you're making an object with properties 0, 3, and 6 set to the given values. Then, the properties are accessed with char[i], which returns null unless the property is defined -- so for all i except 0, 3, and 6, it'll default to ''. For 0, 3, and 6, it'll take the relevant strings.
Alright, I think I figured out what's 'not working', though again I'd need you to explain what that means before I can be sure.
This line:
obj.value += (char[i]||'') + numbers[i];
will insert undefined in the string if numbers[i] isn't defined, and numbers[i] is only defined for i = 0, 3, or 6. Change the line to this:
obj.value += (char[i]||'') + (numbers[i]||'');
and it should work.
It creates an object:
obj = {0:'(',3:') ',6:' - '};
You have two elements inside your object with keys 0, 3 and 6. You can access them obj[0], obj[3] and obj[6]
Or you can access them in a loop as you did in your example
That is a Javascript object.
In addition to creating objects using a constructor function, you can
create objects using an object initializer. Using object initializers
is sometimes referred to as creating objects with literal notation.
"Object initializer" is consistent with the terminology used by C++.
The syntax for an object using an object initializer is:
var obj = { property_1: value_1, // property_# may be an identifier...
2: value_2, // or a number...
// ...,
"property n": value_n }; // or a string
where obj is the name of the new object, each property_i is an
identifier (either a name, a number, or a string literal), and each
value_i is an expression whose value is assigned to the
property_i.
The rest of this article is available here.

mongdb/nodejs: using variables in $inc doesn't work

I have the following that i entered into the mongo terminal and it works great
db.cars.update({'_id':'FordXdfg'},{$inc :{'attribs.0.totl':1}})
which basically updates an array using dot notation, the 0 is the index of the array.
this does work. but transferring it to node my 0 comes from a variable.
so i tried
var carIndex = 3;
cars.update({'_id':'FordXdfg'},{$inc :{'attribs.' + carIndex + '.totl':1}}, function (err, callback) ................)
seems to be invalid javascript, if i replace my carIndex with 3 then it works i.e.
cars.update({'_id':'FordXdfg'},{$inc :{'attribs.3.totl':1}}, function (err, callback) ................)
Any ideas?
thanks
When using that style of object initialization in JavaScript, property names must be string literals. When using the object initialization syntax, property names can not be constructed at run time in code. For example, you can only use literals like:
{
"name": "Martin"
"location": "Earth"
"value": 1234
}
You cannot do this:
var propName = "name";
var obj = {
propName: "Martin";
};
While it syntactically appears to work, you'll end up with an object that looks like:
{
propName: "Martin"
}
Again, that's because only literal values are accepted when constructing an object using the shortened syntax. It will not interpret variable values.
There are two other options for setting properties of a JavaScript object, either through simple dot-notation:
obj.name = "Martin";
Or, you can use bracket notation:
obj["name"] = "Martin";
As objects in JavaScript act like associative arrays in that you can define new properties/keys at runtime each with a value, either syntax above works, and both result in the same underlying storage (and can be used interchangeably).
So, you'll need to construct the $inc syntax separately using the other technique for setting object property values in JavaScript:
var inc = {};
inc["attribs." + carIndx + ".totl"] = 1;
Then use that inside of your update:
{ $inc: inc }

Get values from object if the name of the object is stored as a variable?

I have a JSON object return with the following format:
"miscObject": {
"205": [
{
"h": "Foo",
"l": "Bar"
}
]
}
miscObject contains somewhere over 1500 entries, each named incrementally.
How can I get to the values of 'miscObject.205.h' and 'miscObject.205.l' if I have "205" stored in variable without having to loop through all of the objects inside miscObject?
It seems that you're talking about Javascript objects rather than a JSON string.
x[y] and x.y are mostly interchangeable when accessing properties of Javascript objects, with the distinction that y in the former may be an expression.
Take advantage of this to solve your problem, like so:
var num = '205';
console.log(miscObject[num].l);
// ^^^^^
// \
// instead of `.num`, which wouldn't be the same as
// `num` is not the literal name of the property
Use the member lookup syntax
var miscObject = $.parseJSON(theJsonString);
var name = '205';
miscObject[name].h;
Object values can be accessed 2 ways--using the 'dot' notation as you mentioned, or by using []'s:
The following should work:
var result = miscObject["205"].h;
var miscObject = JSON.parse(your-JSON-object);
var value = miscObject['205'].h
You can do this to get the object:
num = '205'
miscObject[num]

Can I create a method in an object?

I saw this code before, but I don't know what the meaning:
var person1 = {
toLocaleString : function(){
return "Nikolaos";
},
toString : function(){
return "Nicholas";
}
}
var person2 = {
toLocaleString : function(){
return "bum";
},
toString : function(){
return "Greg";
}
}
var people = [person1, person2];
alert(people.toString());
alert(people.toLocaleString());
does the function create an object with the method of toLocaleString and toString??or...??
That code is doing three things:
Using object literal syntax to create object instances
Using anonymous function expressions to create functions and bind them to properties on the objects. (Functions are first-class objects in JavaScript, so you can keep references to them, pass the references around, etc.)
Specifically, it's overriding two standard functions that all JavaScript objects inherit from the Object prototype.
Let's break it down a bit.
1) Object literal notation:
var obj = {propName: propValue};
The { and } in this case denote an object literal. Within an object literal, you can write propName: propValue to assign propValue to the property with the name propName on the object. This is the same as:
var obj = {}; // Get an empty object
obj.propName = propValue; // Add a property to it
You can do multiple properties separated with commas. So for instance:
var obj = {
author: "Douglas Adams",
title: "The Hitchhiker's Guide to the Galaxy",
answer: 42
};
That creates an object with three properties, two with string values and one with a number value.
Note that the right-hand side are processed just like an assignment, and so can be anything that can appear on the right-hand side of an assignment statement:
var x = "bar";
var obj = {
three: 1 + 2,
fubar: "foo " + x
};
The property names can be put in quotes if you like:
var x = "bar";
var obj = {
"three": 1 + 2,
"fubar": "foo " + x
};
...which is handy for specifying properties that have the names of reserved tokens (like "if", or "return") or formerly-reserved tokens (like "class") where it would be a syntax error if they weren't in quotes.
2) Now let's look at function expressions:
var f = function() { /* your code here */ };
That's a function expression. It creates a new function and assigns a reference to it to the variable f. You can call it by calling f().
var f = function(name) {
alert("Hi " + name);
};
f("Fred"); // alerts "Hi Fred"
1 + 2) So putting it together with object literal notation:
var obj = {
foo: function(name) {
alert("Hi " + name);
}
};
obj.foo("Fred"); // alerts "Hi Fred"
(I don't like anonymous functions, I prefer my functions to have names, but that's another topic.)
3) And finally: As maerics pointed out, the specific functions that are being used in that code are toString and toLocaleString, both of which are standard functions of JavaScript objects. That means that those will override the standard version and so return the given values whenever the standard function would have been called.
The toString() and toLocaleString() methods are implemented for all JavaScript objects by the specification of the language. So arrays (such as the one stored in the "people" variable) seem to implement those methods by returning each of their elements' string or "locale string" value, respectively (at least, in the web browsers we are testing).
That is, the Array class toString and toLocaleString methods must be implemented with something like:
Array.prototype.toString = function() {
var a = [];
for (var i=0; i<this.length; i++) {
a[i] = this[i].toString(); // Note "toString".
}
return a.join(",");
}
Array.prototype.toLocaleString = function() {
var a = [];
for (var i=0; i<this.length; i++) {
a[i] = this[i].toLocaleString(); // Note "toLocaleString".
}
return a.join(",");
}

Categories