Add a child to a JavaScript object with a variable name - javascript

Let's say I have a blank JavaScript object:
myObject {}
And I also have a variable:
var myChildObject = this.name.split('.')[1];
For the sake of an example, let's say that myChildObject equals "FooBar". Now, I want to add a child object to myObject with the name of "FooBar", only we can't hard code "FooBar". We have to use the variable name myChildObject.
I tried this:
myObject.appendChild(myChildObject);
That doesn't work.
The goal is this:
{
"myObject":{
"FooBar":{
"thing1":25,
"thing2":6
},
.....
}
But I need to build the entire thing dynamically, without the names (other than the root) being known ahead of time.

An object is a "key value" type of thing, a little bit like a Map in Java. have you tried something like this:
let myObject = {};
let myChildObject = "fooBar";
myObject[myChildObject] = {};
This way you have a "fooBar" key for your Object... now you have to decide what you want the value to be for that key.

Objects can only have key value pair. You cannot use one without other. If you don't want to assign a value then simply give undefined. If you don't know the name of the property then you can simply use the array type notation for an object "[]". Refer to code below
var myObject = {};
var myChildObject = this.name.split('.')[1];
myObject[myChildObject] = undefined;
console.log(myObject.hasOwnProperty(myChildObject)); // true

var myObject = {};
var myChildObject = this.name.split('.')[1];
myObject[myChildObject] ={
"thing1":25,
"thing2":6
};

I'd say
for(var key in myChildObject) {
myObject[key] = myChildObject[key]
}

No idea what your question means but myObject["foobar"] might be what you are looking for

Related

Mongoose update on a string variable not working? [duplicate]

It's difficult to explain the case by words, let me give an example:
var myObj = {
'name': 'Umut',
'age' : 34
};
var prop = 'name';
var value = 'Onur';
myObj[name] = value; // This does not work
eval('myObj.' + name) = value; //Bad coding ;)
How can I set a variable property with variable value in a JavaScript object?
myObj[prop] = value;
That should work. You mixed up the name of the variable and its value. But indexing an object with strings to get at its properties works fine in JavaScript.
myObj.name=value
or
myObj['name']=value (Quotes are required)
Both of these are interchangeable.
Edit: I'm guessing you meant myObj[prop] = value, instead of myObj[name] = value. Second syntax works fine: http://jsfiddle.net/waitinforatrain/dNjvb/1/
You can get the property the same way as you set it.
foo = {
bar: "value"
}
You set the value
foo["bar"] = "baz";
To get the value
foo["bar"]
will return "baz".
You could also create something that would be similar to a value object (vo);
SomeModelClassNameVO.js;
function SomeModelClassNameVO(name,id) {
this.name = name;
this.id = id;
}
Than you can just do;
var someModelClassNameVO = new someModelClassNameVO('name',1);
console.log(someModelClassNameVO.name);
simple as this
myObj.name = value;
When you create an object myObj as you have, think of it more like a dictionary. In this case, it has two keys, name, and age.
You can access these dictionaries in two ways:
Like an array (e.g. myObj[name]); or
Like a property (e.g. myObj.name); do note that some properties are reserved, so the first method is preferred.
You should be able to access it as a property without any problems. However, to access it as an array, you'll need to treat the key like a string.
myObj["name"]
Otherwise, javascript will assume that name is a variable, and since you haven't created a variable called name, it won't be able to access the key you're expecting.
You could do the following:
var currentObj = {
name: 'Umut',
age : 34
};
var newValues = {
name: 'Onur',
}
Option 1:
currentObj = Object.assign(currentObj, newValues);
Option 2:
currentObj = {...currentObj, ...newValues};
Option 3:
Object.keys(newValues).forEach(key => {
currentObj[key] = newValues[key];
});

Getting data from an object with a generated key

Lets assume I have an object like this.
var foo = {
"dfsghasdgsad":{
"name":"bob",
"age":"27"
}
};
foo will always have just one object but the key is generated. How do I retrieve "bob" and "27" in a situation where I won't know what the generated key name will be?
Use Object.keys:
var key = Object.keys(foo)[0];
var name = foo[key].name;
Use Object.keys to get a list of the keys:
var name = foo[Object.keys(foo)[0]].name;

Javascript setter and getter with key for object

I have an object in a variable var o={};
I want to do something like what .push() method doing in array for my object.
JS code:
// Array:
var ar=[];
ar.push('omid');
ar.push('F');
var got=ar[1];
// above code is standard but not what I'm looking for !
/*-------------------------------------*/
// Object:
var obj={};
/* obj.push('key','value'); // I want do something like this
var got2=obj.getVal('key'); // And this
*/
Is this possible at all ?
var obj = {}
// use this if you are hardcoding the key names
obj.key = 'value'
obj.key // => 'value'
// use this if you have strings with the key names in them
obj['key2'] = 'value'
obj['key2'] // => 'value'
// also use the second method if you have keys with odd names
obj.! = 'value' // => SyntaxError
obj['!'] = 'value' // => OK
Since Object-Literals use a Key->Value model, there is no JS method to "push" a value.
You can either use Dot Notation:
var Obj = {};
Obj.foo = "bar";
console.log(Obj);
Or Bracket Notation:
var Obj = {},
foo = "foo";
Obj[foo] = "bar";
Obj["bar"] = "foo";
console.log(Obj);
Consider reading https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects, as arming yourself with this knowledge will be invaluable in the future.
Here is some javascript magic that makes it work.
Take a look.
var obj = {};
Object.defineProperty(obj,'push',{
value:function(x,y){
this[x]=y;
}
});
obj.push('name','whattttt'); <<<this works!!!
obj;
//{name:'whattttt'}
obj.name or obj['name']..
//whattttt
The reason i defined .push function using Object.defineProperty because i didn't want it to show up as a property of object. So if you have 3 items in object this would have always been the 4th one. And mess up the loops always. However, using this method. You can make properties hidden but accessible.
Though i don't know why you would use this method when there is already a easy way to do it.
to assign a value do this
obj.variable = 'value';
if value key is number or weird do this...
obj[1] = 'yes';
to access number or weird name you also do that
obj[1];
and finally to assign random keys or key that has been generated in code, not hard coded, than use this form too.
var person= 'him';
obj[him]='hello';

javascript get json inner value

Let's I have next object
var o = { "foo" : {"bar" : "omg"} };
I can get value of key foo using
o["foo"] // return {"bar" : "omg"}
and I can get value of key bar inside foo using
o["foo"]["bar"] // return "omg"
Can I get value of key bar inside foo using brackets [] single time.
Somethong like
o["foo.bar"] // not working(
or
o["foo/bar"] // not working(
It is fairly common to create a getter function to do something like this. From the comment:
I have object o and string 'foo.bar', and i want get "omg".
var getProp = function (theObject, propString) {
var current = theObject;
var split = propString.split('.');
for (var i = 0; i < split.length; i++) {
if (current.hasOwnProperty(split[i])) {
current = current[split[i]];
}
}
return current;
};
http://jsfiddle.net/MXu2M/
Note: this is a thrown together example, you'd want to bullet proof and buff it up before dropping it on your site.
No, you must use o["foo"]["bar"] because it's an object inside another object. If you want to access it with "foo.bar", it means you must create the first object like this:
var o = {"foo.bar": "omg"}
o["foo.bar"] or o["foo/bar"] are not valid for your example. You could use this notation that is cleaner:
var bar = o.foo.bar // bar will contain 'omg'
there is a way, but I'm not sure this is what you asked for:
eval("o.foo.bar");
it is dangerous though, and doesn't use [] , but if what you want is to use a string for accessing any object it works
Unfortunately, you can only use o["foo"]["bar"] or o.foo.bar

Change key in js associative array

If I have:
var myArray = new Array();
myArray['hello'] = value;
How can I change the key 'hello' to something else?
Something like this would work.
var from = 'hello',
to = 'world',
i, value = myArray[from];
for( i in myArray )
if( i == from ) myArray.splice( i, 1 );
myArray[to] = value;
But is there a native function or a better way to do it?
edit:
Due to the lack of associative arrays in js, what I want to do modify the property name of an object as efficiently as possible.
In JavaScript there is no such thing as associative Array. Objects can be used instead:
var myHash = new Object();
or
var myHash = {};
replace can be done like this:
myHash["from"] = "value";
myHash["to"] = myHash["from"];
delete myHash["from"];
but the preferred way to write it:
myHash.from = "value";
myHash.to = myHash.from;
delete myHash.from;
You can't really "change" the property name, but you can always assign a property value to a new name, and then delete the original one.
myArray['world'] = myArray.hello;
delete myArray.hello;
Also, you're working with an Array instance but using it as a simple object; everything you're doing would work just as well with:
var myArray = {};
The "splice()" you're attempting in the code posted won't work, because it's only for the actual integer-indexed array properties, and not the named properties.
That "delete" doesn't really delete a property really doesn't matter. The "undefined" value is what you get when you check an object for a property and there's no such property.

Categories

Resources