This question already has answers here:
Convert string in dot notation to get the object reference [duplicate]
(6 answers)
is it evil to use eval to convert a string to a function? [closed]
(4 answers)
Closed 10 years ago.
Say I have a JSON object like this:
var a = {
"b" : {
"c" : 1
}
}
is there a quick way to get at c when I know the string "b.c" ?
I guess I could split the string by dots then drill down into c from that but I was hoping there was a quick way to do this in one go.
like I was hoping maybe var c = a["b.c"] but that doesnt work
How about something like this, as you suggested using a split:
var a = {
"b" : {
"c" : 1
}
}
var n = "b.c".split(".");
var x = a;
for(var i = 0; i < n.length; i++){
x = x[n[i]];
}
//x should now equal a.b.c
Here is a working example
In the event that the path is not valid, there is some extra checking that should be done. As my code stands above, x will be undefined if the final part of the path is invalid (e.g "b.d"). If any other part of the path is invalid (e.g. "d.c") then the javascript will error.
Here is a modified example that will end the loop at the first instance of undefined, this will leave x as undefined and will ensure the javascript can continue to execute (no error!)...
var n = "d.c".split(".");
var x = a;
for (var i = 0; i < n.length; i++) {
x = x[n[i]];
if (typeof(x) == "undefined") {
break;
}
}
Here is an example of this in action
var a = {
"b" : {
"c" : 1
}
}
var c = "b.c".split(".").reduce(function(obj, key) {
return obj[key];
}, a);
alert(c)
See reduce. The link also show a how to implement shim for the browsers that doesn't support ES5. Notice that this code is simplified, assumes the keys are present in the objects.
Related
This question already has answers here:
What does the following code mean in javascript? [duplicate]
(2 answers)
Closed 6 years ago.
javaScript(variable)
var s = s || {};
s.c = {};
what purposes it will be use?
var s = s || {};
This means that if s is null, undefined or false (it computes to false), then an empty object {} will be assigned to s, so that the second line would not cause an error.
But this notation is inacurate. It should be something like:
var s = (typeof s == 'object') ? s : {};
because in the first example if s is a number the second line will still cause an error.
In the second example notation A ? B : C; is equal to:
if(A){
B;
}else{
C;
}
This question already has answers here:
How to check if object property exists with a variable holding the property name?
(11 answers)
Closed 7 years ago.
So, I have following js :
var NAMES = {
'185' : {
'FIRST' : 'first',
'MIDDLE' : 'middle',
'LAST' : 'last'
}
};
for (var j = 0; j < (id.length); j++) {
var uDATA_ID = id[j]; //string
var uDATA_OBJ = JSON.parse(uDATA_ID); //converted to object
if (uDATA_ID == NAMES.uDATA_OBJ){
alert("Somethings happening");
}
}
So, I get a string of ids from php. I need to check if this number is available in the object variable.
However, I am having a hard time making it work.
Could someone help me out?
Thanks
To use a variable to access an object field, use the [field] syntax instead of the .field syntax:
var data = NAMES[uDATA_ID]
If that field is missing, it will return undefined (which you can then check for)
if (data) { // assumes you don't want `false` or `0`.
This question already has answers here:
What does ':' (colon) do in JavaScript?
(11 answers)
Closed 7 years ago.
I'm seeing : used in JavaScript a good bit and I can not figure out what exactly what its doing. Is it naming something? For example is the function being named onSave? Example is below.
onSave: function() {
var properties = this.getFormData(),
request = this.wfsBody("usa", "usa:pecotest", "geom",
properties);
console.log(request);
this.makeRequest(request);enter code here
There are, as far as I know, four uses of : in JavaScript. The ternary operator, switch statements, labels, and part of JavaScript object creation.
// if a, then f is b. Otherwise it is C.
var f = a? b: c;
// This creates an object. You can now look at the object's `name` property.
var obj = {name: val}
switch(foo)
{
case 1:
// this only happens if foo === 1
break;
}
top: // this is a label
for (i = 0; items.length; i++)
for (j = 0; j < tests.length; i++)
if (!tests[j].pass(items[i])){
allPass = false;
break top; // breaks the outermost loop.
}
You'll see this also in JSON, which is JavaScript object notation:
{
"foo": 1,
"bar": [2,3],
"baz": {
"bat": 4
}
}
That is an object where
obj.foo === 1
obj.bar[0] === 2
obj.bar[1] === 3
obj.baz.bat === 4
The most common use, and certainly what most people expect when they see the above code, is that an object is being created with a property "onStart" which is a function defined as above.
: is used as an = in an object - separating the object property from its value. Objects can also have functions as values. So what you're seeing is:
var obj = {
onSave: function(){}
}
could also be obj.onSave = function(){}
This question already has answers here:
Convert string in dot notation to get the object reference [duplicate]
(6 answers)
Closed 8 years ago.
I would like to split the str (dot seperated) and look inside an object tree, if the values exist.
To keep it simple, I have just create a simple object, but I would like it to be a deep search.
I just need the logic not necessary a working code, just a direction on what I need to do inside the exists to, check recursebly if person.name.first does exist with a boolean value true || false to be returned as the final answer.
var str = "person.name.first";
var arr = {
person: {
name: {'first':true ,'last' : true },
age : true
}
}
function exists(){
...
}
exists(str,arr);//true === exists, false === does not exist
Just try with:
function exists(str, arr) {
var parts = str.split('.');
for (var i = 0; i < parts.length; i++ ) {
if (arr.hasOwnProperty(parts[i])) {
arr = arr[parts[i]];
} else {
return false;
}
}
return true;
}
This question already has answers here:
dynamic keys for object literals in Javascript [duplicate]
(8 answers)
in javascript is it possible to construct an object literal with expressions evaluating to strings for property names? [duplicate]
(2 answers)
variable in javascript statement
(2 answers)
Closed 8 years ago.
I'm bored and messing with my console and I came up with the following code:
I was trying something like:
x = 16;
y = 26;
f = { x+y:"String!"};
expecting something or somehow to do:
Object {1626: "String!"}
Or at least
Object {42: "String!"}
I ended up with
x = 16;
y = 26;
eval("f = { "+x+y+":\"String!\"}");
Which returned as expected:
Object {1626: "String!"}
I've always been told to avoid eval() and never even think about using it due to something about security. Is there a way to use variables in declaring the property (Sorry if I don't know what it's called exactly)
x = 16;
y = 26;
f = {};
f[x+''+y] = "String!"; // For f[1626]
or
f[x+y] = "String!" // For f[42]
I made this exact same mistake when I started learning JavaScript: JavaScript set object key by variable
You first must make the object:
var f = {};
Then you can use variables to dynamically create keys:
var x = 16, y = 26;
f[x+y] = "Integer";
f[x.toString() + y.toString()] = "String";