This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
is it evil to use eval to convert a string to a function? [closed]
(4 answers)
Closed 8 years ago.
I have a a function that takes a string like "obj.key.subkey.subsubkey":
function(obj, key) {
return eval('obj.'+ key);
}
What would be a safe alternative to eval in this case or is eval fine? new Function won't work in this case AFAIK. Maybe split and loop then?
I'm not sure you really need a function here. If you have the object and the key just use the key to return the property on the object.
obj[key]
If you must handle multiple keys:
function get(obj, key) {
var keys = key.split(".");
var tmp = obj;
for (var x = 0; x < keys.length; x++){
tmp = tmp[keys[x]];
}
return tmp;
}
Working Example: http://jsfiddle.net/H55ka/
Related
This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 4 months ago.
I am trying to add a value in place of json object key but it always returns variable name.
My Code:
var projectName='';
let tempArray=[];
let output={};
for(i=0;i<myJsonArray.length;i++){
name = myJsonArray[i].Project;
tempArray.push(myJsonArray[i]);
}
output= {projectName :tempArray};
console.log(JSON.stringify(output));
This returns a JSON as
{"projectName":[{"Day":"MON","Project":"ABC","Billing Rate":"xxx"},{"Day":"TUE","Project":"ABC","Billing Rate":"xyx"}]}
But I need something like this:
{"ABC":[{"Day":"MON","Project":"ABC","Billing Rate":"xxx"},{"Day":"TUE","Project":"ABC","Billing Rate":"xyx"}]}
Can someone help on what I am missing here.
Kind Regards.
You should wrap the project name into [] that would help to make a value become a key
var name = '';
let tempArray = [];
let output = {};
for (i = 0; i < myJsonArray.length; i++) {
name = myJsonArray[i].Project;
tempArray.push(myJsonArray[i]);
}
output = {
[name]: tempArray
};
console.log(JSON.stringify(output));
P/s: I don't see any projectName variable there, so I replace it by name instead.
This question already has answers here:
How do I test for an empty JavaScript object?
(48 answers)
Closed 5 years ago.
This is similar to what I have been trying to do,
var obj = {};
if(obj){
//do something
}
What i want to do is that the condition should fail when the object is empty.
I tried using JSON.stringify(obj) but it still has curly braces('{}') within it.
You could use Object.keys and check the length of the array of the own keys.
function go(o) {
if (Object.keys(o).length) {
console.log(o.foo);
}
}
var obj = {};
go(obj);
obj.foo = 'bar';
go(obj);
You can check if the object is empty, i.e. it has no properties, using
Object.keys(obj).length === 0
Object.keys() returns all properties of the object in an array.
If the array is empty (.length === 0) it means the object is empty.
You can use Object.keys(myObj).length to find out the length of object to find if the object is empty.
working example
var myObj = {};
if(Object.keys(myObj).length>0){
// will not be called
console.log("hello");
}
myObj.test = 'test';
if(Object.keys(myObj).length>0){
console.log("will be called");
}
See details of Object.keys
This question already has answers here:
How can I convert the "arguments" object to an array in JavaScript?
(21 answers)
Closed 7 years ago.
How do I use .forEach instead of a for loop?
'use strict';
var score = (function(){
function updateScore() {
for(var i = 0; i < arguments.length; i++) {
this.score += arguments[i];
}// I want to use .forEach here instead of for loop.
return this.score;
}
return {
update: updateScore
}
})();
var soccer = {
name: 'Soccer',
score: 0
}
score.update.apply(soccer, [1,2,3])
console.log(soccer.score)
this will log 6.
I tried this
function updateScore() {
arguments.forEach((args, i) => {
this.score += args[i];
};
return this.score;
};
Error log: arguments.forEach is not a function
In modern (ES2015) JavaScript you can use Array.from():
Array.from(arguments).forEach((arg) => {
this.score += arg;
});
You don't need to use array indexing, as the .forEach() function passes each array element to the callback function as the first argument. (It does pass the index as the second argument, but in this case you wouldn't need to use that.)
It's important to note that if the arguments object is passed out of a function (as it would be here), the overall function may be considered ineligible for optimization. That's because the arguments object has some weird properties that make it very hard for the optimizer to know what's going on and whether it's safe to make assumptions about how local variables change. If that's a concern, then the only option is to copy the arguments into a simple array with a for loop.
This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 7 years ago.
I want to parse a string to an object object selector like so :
var test = 'object.prop1.prop2';
into
object['prop1']['prop2'];
The problem is i don't know how many properties the string could have.
What is the best way to to parse a string accross, idealy without something like json parse/ eval?
There is a package for that :
https://www.npmjs.com/package/object-path
Juhana's link is excellent, but also a bit more of a complex problem than the one you have here. Here is my take (https://jsfiddle.net/gm32f6fp/3/):
var object = {
prop1: {
prop2: {
foo: 1
}
}
};
function get(object, key) {
var keys = key.split('.');
for (var i = 0; i < keys.length; i++) {
if (!object.hasOwnProperty(keys[i])) {
return null;
}
object = object[keys[i]];
}
return object;
}
console.log(get(object, 'prop1.prop2'));
console.log(get(object, 'prop1.prop3'));
The idea is to take the string of keys, split it based on the dot. Then you have an arbitrarily large array of keys, so we take each key, one by one, and dive into the object. (If we end up at a dead end, we bail out.)
This question already has answers here:
Length of a JavaScript object
(43 answers)
Closed 8 years ago.
Below is my object in JavaScript, how can i calculate the length of it.
var treeObj = {
1: ['96636736','10'],
2 : ['96636734','20'],
3 : ['96636731','45']
};
treeObj .length is not working. any help would be appreciated. Thanks.
You can do this:
Object.getOwnPropertyNames(treeObj).length; // 3
getOwnPropertyNames returns array of properties of treeObj whose length can be checked.
To count the number of properties an object has, you need to loop through the properties but remember to use the hasOwnProperty function:
var count = 0;
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
count++;
}
}
If you forget to do that, you will be looping through inherited properties. If you (or some library) has assigned a function to the prototype of Object, then all objects will seem to have that property, and thus will seem one item "longer" than they intrinsically are.
consider using jQuery's each instead:
var count = 0;
$.each(obj, function(k, v) { count++; });
OR simply,
for (var p in obj)
count++;
UPDATE With current browsers:
Object.keys(someObj).length
Refer Old Post