Getting data from an object with a generated key - javascript

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;

Related

Add a child to a JavaScript object with a variable name

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

JavaScript Custom JSON Names Childs

I am trying to create a JSON Array:
let someJSON = {};
someJSON["number1"] = "someString";
works. But when I want to set a "Child" to number1 it fails:
someJSON["number1"]["date"] = "19.01.2017";
I tried some things but its not working :(
I need to create the JSON like this because I needs variables as parents
I am trying to create a JSON Array:
let someJSON = {};
someJSON["number1"] = "someString";
That's not a JSON array, that's a JavaScript object.
But when I want to set a "Child" to number1 it fails:
someJSON["number1"]["date"] = "19.01.2017";
That's because you're setting a property on a string primative. That will temporarily promote the string primative to an object, set the property, and then throw away the object, effectively doing nothing.
To make someJSON.number an object, create an object just like you did for someJSON and add properties to it. Or you can do it all at once:
let obj = {
number1: {
date: "19.01.2017"
}
};
If you want "someString" in there somewhere, just put it on another property:
let obj = {
number1: {
str: "someString",
date: "19.01.2017"
}
};
You have to create the "number1" object first. Note that you won't be able to set a string value for "number1" as it is now an object.
let someJSON = {};
someJSON["number1"] = {};
someJSON["number1"]["date"] = "19.01.2017";

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];
});

Alternative to variable keys in Meteor

How can I use a variable value as an object key?
For example, when adding an object dynamically to a Collection. When I to do it like this:
addToDB(type, account) {
Accounts.insert({type: account});
};
it doesn't work as the key can't be a variable here.
JavaScript object literal don't support dynamic keys.
Instead you can achieve the goal using :
var obj = {};
var key = "some key";
obj[key] = "test";
In your case:
addToDB(type, account) {
var obj = {};
obj[type] = account;
Accounts.insert(obj);
};
More details here:
Creating object with dynamic keys

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