string as object reference to object variable - javascript

var string = 'object.data.path';
That's a string that resembles a path to variable.
How can I return the corresponding variable from that string?
Something like transforming the string into return object.data.path;
The thing behind this is that the string could be much longer (deeper), like:
var string = 'object.data.path.original.result';

function GetPropertyByString(stringRepresentation) {
var properties = stringRepresentation.split("."),
myTempObject = window[properties[0]];
for (var i = 1, length = properties.length; i<length; i++) {
myTempObject = myTempObject[properties[i]];
}
return myTempObject;
}
alert(GetPropertyByString("object.data.path"));
this assumes that your first level object (in this case called object is global though.
Alternatively, although not recommended, you could use the eval function.

Assuming you don't want to just use eval you could try something like this:
function stringToObjRef(str) {
var keys = str.split('.'),
obj = window;
for (var i=0; i < keys.length; i++) {
if (keys[i] in obj)
obj = obj[keys[i]];
else
return;
}
return obj;
}
console.log(stringToObjRef('object.data.path.original.result'));
Uses a for loop to go one level down at a time, returning undefined if a particular key in the chain is undefined.

Related

Create object with key:value in one line

I need implement this in one line, if possible:
I have an object
var object1 = {};
object1['key_1'] = "value_1";
object1['key_2'] = "value_2";
object1['key_3'] = "value_3";
I need pass to an function one item from object (not only value ), key - only string value
for (var key in object1)
FunctionTemp({key:object1[key]}); // - this don't work as I need, and eval() method I don't want
maybe there is something like this
FunctionTemp((new {})[key]=object1[key]) - its don't work!!! :)
Since you really want it in one line you can do it like this:
var temp;
for (var key in object1)
FunctionTemp(((temp = {}) && (temp[key] = object1[key]))? temp: null);
but I think it is no longer readable as it is, the most ideal solution would be to break it down into several lines.
var temp;
for (var key in object1) {
temp = {};
temp[key] = object1[key];
FunctionTemp(temp);
}
What you're asking for is not possible without a function.
What you want to do is this:
var key = getKey(); //some means of determining a key dynamically
var val = getVal(); //some means of determining a value dynamically
var obj = {};
obj[key] = val;
this.doSomething(obj);
What you need is another method that assembles the object based on the dynamic key/value.
this.doSomething(_.object([[getKey(), getVal()]]));

How do I access a Javascript 2D array of objects?

I have a global array that I declare as
var fileMappings = [];
I do some work, and add a row to the array like so:
fileMappings.push({ buttonNumber: number, audioFile: file });
if I do a JSON.stringify(fileMappings) I get this:
[{“buttonNumber”:”btn11”,”audioFile”:{0A0990BC-8AC8-4C1C-B089-D7F0B30DF858}},
{“buttonNumber”:”btn12”,”audioFile”:{2FCC34A6-BD1A-4798-BB28-131F3B546BB6}},
{“buttonNumber”:”btn13”,”audioFile”:{53A206EC-7477-4E65-98CC-7154B347E331}}]
How can I access the GUID for "btn11", etc?
Since Javascript arrays don't have support for keys, I would suggest that you use an object. Otherwise, you have to iterate through the entire array every time to look for the desired key.
var fileMappings = {};
And instead of push(), define a new property :
fileMappings[number] = { buttonNumber: number, audioFile: file };
This way, you can access your object with fileMappings['btn11']
You can iterate over the array's members to find the button, then return its GUID:
function findGUID(arr, buttonNumber) {
for (var i=0, iLen=arr.length; i<iLen; i++) [
if (arr[i].buttonNumber == buttonNumber) {
return arr[i].audioFile;
}
}
// return undefined - buttonNumber not found
}
Or if you want to use ES5 features:
function getGUID(arr, buttonNumber) {
var guid;
arr.some(function(obj) {
return obj.buttonNumber == buttonNumber && (guid = obj.audioFile);
});
return guid;
}
but I think the first is simpler and easier to maintain.

Converting a string to a javascript associative array

I have a string
string = "masterkey[key1][key2]";
I want to create an associative array out of that, so that it evaluates to:
{
masterkey: {
key1: {
key2: value
}
}
}
I have tried this:
var fullName = string;
fullName = fullName.replace(/\[/g, '["');
fullName = fullName.replace(/\]/g, '"]');
eval("var "+fullName+";");
But I get the error: missing ; before statement with an arrow pointing to the first bracket in ([) "var masterkey["key1"]["key2"];"
I know that eval() is not good to use, so if you have any suggestions, preferably without using it, I'd really appreciate it!
Not the most beautiful, but it worked for me:
var
path = "masterkey[key1][key2]",
scope = {};
function helper(scope, path, value) {
var path = path.split('['), i = 0, lim = path.length;
for (; i < lim; i += 1) {
path[i] = path[i].replace(/\]/g, '');
if (typeof scope[path[i]] === 'undefined') {
scope[path[i]] = {};
}
if (i === lim - 1) {
scope[path[i]] = value;
}
else {
scope = scope[path[i]];
}
}
}
helper(scope, path, 'somevalue');
console.log(scope);
demo: http://jsfiddle.net/hR8yM/
function parse(s, obj) {
s.match(/\w+/g).reduce(function(o, p) { return o[p] = {} }, obj);
return obj;
}
console.dir(parse("masterkey[key1][key2]", {}))
Now try this
string = "masterkey[key1][key2]";
var fullName = string;
fullName = fullName.replace(/\[/g, '[\'');
fullName = fullName.replace(/\]/g, '\']');
document.write("var "+fullName+";");
1) When using eval, the argument you provide must be valid, complete javascript.
The line
var masterkey["key1"]["key2"];
is not a valid javascript statement.
When assigning a value to a variable, you must use =. Simply concatenating some values on to the end of the variable name will not work.
2) var masterkey = ["key1"]["key2"] doesn't make sense.
This looks like an attempt to assign the "key2" property of the "key1" property of nothing to masterkey.
If you want the result to be like the example object you give, then that is what you need to create. That said, parsing the string properly to create an object is better than using regular expressions to translate it into some script to evaluate.

Javascript: finding a value from an object

I have the following object:
var stuff = {};
stuff["jar"] = "biscuit";
stuff["cupboard"] = "food";
Iterating through the list with an For i loop and getting the value is easy, but how would I get the key?
for (var i in stuff) {
var key = GET KEY SOMEHOW
var val = stuff[i];
}
The key is i. However, make sure that the key is in your object, not part of the prototype chain.
for (var i in stuff) {
var key = i;
if (stuff.hasOwnProperty(i)) {
var val = stuff[i];
}
}
See also:
https://developer.mozilla.org/en/JavaScript/Reference/Statements/for...in
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
var key = i;
In Javascript's for (foo in bar) if foo is the index of an object or array and happens to be a string, it should print or assign the string when called.
You already have it:
for (var key in stuff) {
var val = stuff[key];
}
If you have the value already you may find the key by using this logic :
for (var i=0;i<numKeyValuePairs;i++)
{
if(val==key[i])
{
document.write(key[i];
}
}

Dynamically create Instance fields for a JavaScript Object

I have a dynamically-created list of strings called 'variables'. I need to use these strings as the instance variables for an array of JavaScript objects.
var objectsArr = [];
function obj(){};
for (var i=0; i<someNumberOfObjects; i++ ) {
...
objectsArr[i] = new Object();
for (var j=0; j<variables.length; j++) {
objectArr[i].b = 'something'; //<--this works, but...
//objectArr[i].variables[j] = 'something'; //<---this is what I want to do.
}
}
The commented-out line shows what I am trying to do.
You can use the bracket syntax to manipulate the property by name:
objectArr[i][variables[j]] = 'something';
In other words, get the object from objectArr at index i then find the field with name variables[j] and set the value of that field to 'something'.
In general terms, given object o:
var o = {};
You can set the property by name:
o['propertyName'] = 'value';
And access it in the usual way:
alert(o.propertyName);
Use the bracket notation. This will get it done:
var objectsArr = [], ii, jj;
function Obj() {}
for(ii = 0; ii < someNumberOfObjects; ii += 1) {
objectsArr[ii] = new Obj();
for (jj = 0; jj < variables.length; jj += 1) {
objectArr[ii][variables[jj]] = 'something';
}
}
A couple of additional notes:
Javascript doesn't have block scope, so you must have two separate loop variables.
By convention, constructor functions like Obj should begin with a capital letter to signify that they ought to be used with the new keyword. In this case though, unless you need the objects to have a non-Object prototype, you could just use a plain object literal (objectsArr[ii] = {};).

Categories

Resources