Get link to nested object by string key - javascript

For example, I have an object:
var model = {user:{name: 'Mike', phones:{mobile: '00000'}}};
and a string key:
var string_key = 'user.phones.mobile';
I can parse it to get the array key:
var keys = string_key.split('.');
How can I can get link to object phones from model?

By doing this:
model[keys[0]][keys[1]][keys[2]];
This seems a bit strange though..

Related

Unable to get the value from a JavaScript object

I have created a JSON object and put it under session object.
How can I retrieve the value from the JSON?
This is my program
var datainsession = {"firstName":"John", "lastName":"Doe"};
var keyname = 'test';
window.sessionStorage.setItem(keyname + '', datainsession);
var val_sess = window.sessionStorage.getItem(keyname);
var firstname = val_sess.firstName;
alert(firstname);
http://jsfiddle.net/5bea0mr2/3/
Could you please tell me how I can retrieve the first name?
Session storage can only hold strings, not objects. Your session here ends up holding your object converted to a string ("[Object object]"), and not the object itself.
To get around this we can firstly convert the object to a JSON string using JSON.stringify():
window.sessionStorage.setItem(keyname + '', JSON.stringify(datainsession));
-> '{"firstName":"John","lastName":"Doe"}'
Then when pulling it convert it back to an object by using JSON.parse():
var val_sess = JSON.parse(window.sessionStorage.getItem(keyname));
-> {"firstName":"John","lastName":"Doe"}
window.sessionStorage.setItem can only store serialised objects.
So you have to serialise it first via JSON.stringify:
window.sessionStorage.setItem(keyname, JSON.stringify(datainsession))
Then to retrieve it via JSON.parse:
var val_sess = window.sessionStorage.getItem(keyname);
var obj = JSON.parse(val_sess);
// obj.firstName is what you need.
JSON is represented by a string, not an object. It's simply a JavaScript object with string keys. You'll need to use JSON.stringify() and JSON.parse() to convert the JavaScript object.
Try the following:
var datainsession = {
firstName: "John",
lastName: "Doe"
};
var keyname = 'test';
window.sessionStorage.setItem(keyname, JSON.stringify(datainsession));
var val_sess = JSON.parse(window.sessionStorage.getItem(keyname));
var firstname = val_sess.firstName;
alert(firstname);
You need to convert it to a string on setting, and parse it when you get it out. This method only stores a string, but JSON methods can get around that. Eg.
var datainsession = {"firstName":"John", "lastName":"Doe"};
var keyname = 'test';
window.sessionStorage.setItem(keyname + '', JSON.stringify(datainsession));
var val_sess = window.sessionStorage.getItem('test');
var obj = JSON.parse(val_sess).firstName;
alert(obj);

Can Javascript objects be accessed like arrays?

Assuming an object is initialized as following:
var myObj = {
"key1":"val1",
"key2":"val2",
"key3":"val3",
...
};
Can I retrieve key values like this?
var retrKey1 = myObj[0];
var retrKey2 = myObj[1];
var retrKey3 = myObj[2];
...
The issue I am trying to solve is that I need to pick random key values from this object. Generating a random number is not an issue, but:
How can I retrieve the number of keys in the object/map?
Can I retrieve the key values using a integer index like in arrays?
If not, what are my options?
The Object.keys method returns an array of object properties. You can index the array with numbers then.
var myObj = {
"key1":"val1",
"key2":"val2",
"key3":"val3",
...
};
var keys = Object.keys(myObj);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
No, because there's no ordering among property keys. If you want ordered keys, you need to work with an array.
You could define a structure like this :
var myObj = [
{key:"key1", val:"val1"},
...
];

Creating a 2d associative array javascript (same as a php assoc array)

I am trying to create an array in javascript which will allow me to access data like this:
var name = infArray[0]['name'];
however I cant seem to get anything to work in this way. When i passed out a assoc array from php to javascript using json_encode it structured the data in this way.
The reason why i have done this is so i can pass back the data in the same format to php to execute an update sql request.
JavaScript doesn't have associative arrays. It has (numeric) arrays and objects.
What you want is a mix of both. Something like this:
var infArray = [{
name: 'Test',
hash: 'abc'
}, {
name: 'something',
hash: 'xyz'
}];
Then you can access it like you show:
var name = infArray[0]['name']; // 'test'
or using dot notation:
var name = infArray[0].name; // 'test'
simply var infArray = [{name: 'John'}, {name: 'Greg'}] ;-)
JavaScript doesn't have assoc arrays. Anything to any object declared as obj['somthing'] is equal to obj.something - and it is a property. Moreover in arrays it can be a bit misleading, so any added property won't changed array set try obj.length.
JavaScript do not have 2D associative array as such. But 2d associative array can be realized through below code:
var myArr = { K1: {
K11: 'K11 val',
K12: 'K12 Val'
},
K2: {
K21: 'K21 Val',
K22: 'K22 Val'
}
};
alert(myArr['K1']['K11']);
alert(myArr['K1']['K12']);
alert(myArr['K2']['K21']);
alert(myArr['K2']['K22']);

add anonymous object to an object

I know to add a named object to an existing JavaScript object you do this:
var json = {};
json.a = {name:"a"};
But how can you add an object to an existing JavaScript object in a similar fashion without assigning it an associative name, so that it could be accessed by a for() statement. Sorry if I'm being a little vague, I don't know a lot about JavaScript objects.
UPDATE:
I want the end result to look like this:
var json = [{name:'a'}{name:'b'}];
What you have there is not strictly a JSON object. You're using JS object literals rather.
You can do this:
var jsObj = {};
// add a 'name' property
jsObj = { name: 'a'};
var anotherObj = { other: "b" };
// will add 'other' proprty to jsObj
$.extend(jsObj, anotherObj);
// jsObj becomes - {name: 'a', other:'b'}
The JSON representation of above will look like:
var jsonString = "{'name': 'a', 'other':'b'}";
// will give you back jsObj.
var jsonObj = JSON.Parse(jsonString); // eval(jsonString) in older browsers
Note that you cannot have property without a name. This is not valid:
// invalid, will throw error
jsObj = { : 'a'};
Try an array that you push an item on to using
myArrayVar.push(value);
or
myArrayVar[myArrayVar.length] = value;
It makes no sense to have a property of an object without a property name. A "for ... in" loop is a loop over that collection of property names, after all. That is,
for (var k in obj)
will set "k" equal to each of the names of properties in "obj" in turn.
You cannot do this, because a JSON object is a collection of string-value pairs. A value can be an array, and you can push your object into that array, without an associative name.
http://www.json.org/
What you are describing is an array of objects.
var j = [{name:'a'},{name:'b'}];
This has the properties you are looking for. You can operate on it like so:
for(var i in j) {
alert(j[i].name);
}

Efficient syntax for populating a javascript associative array

I have an autocomplete text box that users can type an item code into and need to find out what the id number of that item code is in javascript.
An associative array is the way I would imagine it should be done, but the following seems a little long winded and I'm hoping someone has a better way to do it or shorthand of what I have below:
var itemIds = new Array();
itemIds["item1"] = 15;
itemIds["item2"] = 40;
itemIds["item3"] = 72;
...
function getItemId(code){
return itemIds[code];
}
What you're doing isn't an array - it's an object (objects in JavaScript are the equivalent-ish of associative arrays in PHP).
You can use JavaScript object literal syntax:
var itemIds = {
item1: 15,
item2: 40,
item3: 72
};
JavaScript object members can be accessed via dot notation or array subscript, like so:
itemIds.item1;
itemIds['item1'];
You'll need to use the second option if you've got the member name as a string.
Try using Object Literal notation to specify your lookup like this:
var itemIds = {
"item1" : 15,
"item2" : 40
...
};
Access should still work like this:
var item1Value = itemIds["item1"];

Categories