Say I have the following:
var a = '1',
b = 'foo';
How do I create an object using the above variables such that my object looks like this:
'1' => 'foo'
I'm trying to make this like an associative array. Furthermore, I want 1 to contain an array of objects. I have the variable that have the array of object; I just need to put it in 1.
Use an object literal:
var myObject = { "1" : "foo" };
or, if you want to create it from variables, create a new object then assign things.
var myObject = {};
myObject[a] = b;
Furthermore, I want 1 to contain an array of objects
JavaScript doesn't care what type the data is. b can be an array as easily as a string. (And you can use an array literal where you have a string literal in the short version)
var myObject = { "1" : [ 7, "foo", new Date() ] };
var obj = { '1' : 'foo' };
obj['1']; // returns 'foo'
or
var obj = { '1' : new Array() };
obj['1']; // returns an array
To do literally what you asked:
var a = '1',
b = 'foo',
o = {};
o[a] = b;
Quentin has the rest of the answer.
Edit
An example of assigning an object to an object property:
var foo = {bar: 'baz'};
var obj = {foo: foo};
// or
// var obj = {};
// obj['foo'] = foo;
// or
// obj.foo = foo;
alert(obj.foo.bar); // baz
Related
I have an empty object and want to create an object inside object dynamically.
const obj = {}
obj["test1"]["test1.1"] = x //initialize to some variable
I get the error
Uncaught TypeError: Cannot set property 'test1.1' of undefined
I want the output to be like
obj = {
test1: {
test1.1: x //some variable
}
}
By dynamically if you mean the name of the attribute is not certain, you can use brackets to insert dynamic variable names:
const arg1 = 'test1';
const arg2 = 'test1.1';
const x = 42;
// assign both variable names dynamically
const obj = { [arg1]: { [arg2]: x } };
console.log(obj);
You can do this in two steps or one
const x = "some var";
const obj = {};
obj["test1"] = {
"test1.1": x
}; // assign the nested object
console.log(obj);
// or
const y = "some var";
const obj1 = { // assign the complete object
test1: {
"test1.1": x
}
};
console.log(obj1);
You need to initialize obj["test1"] = {}
const obj = {}
obj["test1"] = {}
obj["test1"]["test1.1"] = 'x'
console.log(obj)
For the other solution using lodash library, you can use set() method.
var obj = {}
_.set(obj, ["test1", "test1.1"], 'x');
console.log(obj)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>
A more functional approach
const arr = {};
// respecting immutability
const rewroteArray = {...arr, da: {"foo": 2}}
console.log(rewroteArray);
As creating an Object with this syntax const obj = {} is equal const obj = new Object(). You can use the second method to define any level deep of properties definition.
const obj = new Object({
"test1": {
"test-1":'x'
}
});
console.log(obj);
suppose we want to create a new object.
let myObject = {};
and we have some property that exists in another object like :
let b = { foo: "bar"};
is it possible to check if b?.foo append foo to myObject inline in the declaration of the object?
something like this :
let myObject = { b?.foo }
I think the best you can do is :
let myObject = {
some: "prop",
...(b?.foo && {foo:b.foo})
}
Or if you want to pass all the object
let myObject = {
some: "prop",
...(b?.foo && b)
}
I have a use case as follows
var myObject1 = new myObject();
and myObject should have an array which will store all the objects created of this myObject
Example:-
if create an object such as
var xyz = new myObject();
myObject.all[0] == xyz
is there any way where - when I create an object & I can push it into an array which is in the definition of same object.
You can create a property directly on the constructor function, to get the myObject.all[0] == xyz behaviour mentioned in the question. Add each object to the array from within the constructor:
function MyObject() {
MyObject.all.push(this);
// any other initialisation tasks here
}
MyObject.all = [];
var obj1 = new MyObject();
var obj2 = new MyObject();
// to access the array use MyObject.all:
console.log(MyObject.all[1] === obj2); // true
Alternatively, you can add an array to the object prototype, but still add new objects to that array from within the constructor:
function MyObject() {
this.all.push(this);
// any other initialisation tasks here
}
MyObject.prototype.all = [];
var obj1 = new MyObject();
var obj2 = new MyObject();
// to access the array:
console.log(obj1.all);
// or
console.log(MyObject.prototype.all);
console.log(obj1.all[1] === obj2); // true
(Note: in both examples, I've spelled MyObject with a capital "M", because it is a JS convention for functions intended as constructors to be capitalised. This isn't mandatory.)
Maybe something like this?
function MyObject(name){
if (!O.prototype.instances) O.prototype.instances = [];
O.prototype.instances.push(name);
}
var a = MyObject('a');
var b = MyObject('b');
console.log(MyObject.prototype.instances)
Can someone explain what is happening in the code below? I'd expect toString to get called for either both foo and bar, or neither. How is literal object notation different from adding fields to an object after it is created?
function Obj(v) {
this.v = v;
};
Obj.prototype.toString= function() {
window.alert("to string called for " +
this.v);
return this.v.toString();
}
var foo = new Obj('foo');
var bar = new Obj('bar');
// toString is not called here.
var map = {foo : 'blah'};
// toString is called here.
map[bar] = "blah2";
Why do object literals not use toString() while adding to an existing object does use toString()?
http://jsfiddle.net/pByGJ/2/
The main reason that object literals don't evaluate the identifier to the left of the colon is so you're not force to quote all literal names (as you do in JSON).
Bracket notation forces you to quote property names, if you don't, it will be evaluated as a variable.
The reason toString() does get called in the second example is because bar has to be converted to a string to be used as a property name.
In your first example, you're just creating a literal object (that is the exactly the same as {"foo" : 'blah'}). So that is never using the variable foo
If you want to create an object using a variable name, you can't use literal object notation, you have to use [] which is what forces it to call toString()
Here's a function to create objects with variable names in one expression.
function obj(key, value /*, key, value, ... */) {
var obj = {};
for (var i = 0, ln = arguments.length ; i < ln; i+=2) {
obj[arguments[i]] = arguments[i+1];
}
return obj;
}
Clearer Example
The fact that your variable names and values are the same doesn't help understanding the problem. Let me suggest this code
var foo = new Obj('fooValue');
var bar = new Obj('barValue');
var map = {foo : 'blah'};
map[bar] = "blah2";
// You expect map to be {fooValue: 'blah', barValue: 'blah2'}
// But it's {foo: 'blah', barValue: 'blah2'}
To do what you need, use my obj function
// Almost as clear as literal notation ???
var map = obj(
foo, 'blah',
bar, 'blah2'
);
// map = {fooValue: 'blah', barValue: 'blah2'} Yay!!
keys in an object literal are taken as strings, not interpreted as variables. This:
var map = {foo : 'blah'};
is equivalent to this:
var map = {"foo" : 'blah'};
and this:
var map = {};
map["foo"] = "blah";
but is completely different than this:
var map = {};
map[foo] = "blah";
If I have a variable foo that hold a reference to an object:
var foo = someObj;
How can I then use the name of the object as a string?
I tried:
var bar = foo.valueOf()
But that just returned another reference to the object.
What I have is an algorithm that selects from a large number of objects. I then want to use the name of that object to select from amongst a group of HTML elements. Using the following does not work either (returns null):
document.getElementById(foo)
Thank you.
There is no reliable way to get the name of the object.
Example:
var obj = {};
var obj1 = obj;
var obj2 = obj;
magically_get_and_print_name(obj); // What to print? "obj"? "obj1"? "obj2"?
Methods to get the name in some cases:
Function declarations - funcreference.name (non-standard, though well-supported)
Constructor instances - instance.constructor.name
Let's say you have:
var someObj = {
a: 15,
b: 36
};
And then you did:
var foo = someObj;
There's no way to get the string "someObj" (or "foo") from foo.
What you could do, is add the name to the object when creating it. Something like this:
var someObj = {
a: 15,
b: 36,
objName: 'someObj'
};
var foo = someObj;
console.log(foo.objName); // "someObj"