Javascript: turn an array of keys into an empty object? [duplicate] - javascript

This question already has answers here:
How to set object property (of object property of..) given its string name in JavaScript?
(16 answers)
Closed 4 years ago.
I know this is probably easier than my brain is making it, but for some reason, I can't get this right:
I have an array looks like this:
["engine", "engine.car", "engine.car.driver",
"engine.car.passenger", "wheels", "wheels.tires"]
I want to transform above array into this object:
{
engine : {
car : {
driver : undefined,
passenger: undefined
}
},
wheels : {
tires: undefined
}
}
I'm using node 8.10.0.

This is pretty straightforward with JavaScript and the eval functionality. Here is a quick example.
var arr = ["engine", "engine.car", "engine.car.driver", "engine.car.passenger", "wheels", "wheels.tires"];
obj = {};
for(var i = 0; i < arr.length; i++)
eval("obj." + arr[i] + " = {}");
console.log(obj);
Edit
Eval is not evil, most implementations of it are but this is a perfectly valid use of it as outlined in the comments below. If you have an issue with this answer please use the comments to let me know why so I can either update the answer or OP can get the help they need.

Related

Unable to bind javascript variable to JSON object key [duplicate]

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.

Can't use a string in an object path [duplicate]

This question already has answers here:
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Closed 5 years ago.
I have this code :
success(JSON.parse(xhr.responseText).items[0].snippet.title);
The problem is I can access what I want with this but I'd like to be able to do this :
var path = 'items[0].snippet.title';
success(JSON.parse(xhr.responseText).path);
And it doesn't work :(
It's probably nothing but I can't figure out why.
Thanks!
For accessing object properties by string you need to use [ ] notation:
var foo = {bar : 2};
foo['bar']; // 2
But that won't work for nested properties, here is the approach I would follow using Array.reduce and ES6:
let path = 'items.snippet.title';
let response = JSON.parse(xhr.responseText);
let result = path.split('.').reduce((pre,cur) => {
return pre[cur];
}, response);
success(result);
In the first iterarion pre will be response, and cur 'items' returning result.items and so on, it won't work when accesing array indexes though so you will need to add some extra logic inside the reduce function.
const [, cur, position] = cur.match(/^([^\[]+)(?:\[(\d+)])?$/);
// filter foo[1] capturing foo and 1, then assign them using destructuring.
// Thanks for edit!
return ( Array.isArray(pre[cur]) ? pre[cur][position] : pre[cur]);

how to parse string to javascript object selector [duplicate]

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.)

Calulating length in Javascript [duplicate]

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

Define object by a variables string [duplicate]

This question already has answers here:
How do I make JavaScript Object using a variable String to define the class name?
(10 answers)
Using a variable value to call an array element
(7 answers)
Closed 8 years ago.
Hard to explain.. I basicly want to do the following:
var doWhat = "speak";
var speak = {
hello: function() { alert: "Hello!"; }
};
// Won't work
doWhat.hello();
It's a bad example, but you should be able to get what I mean.
Is it possible somehow ?
You can use eval(doWhat).hello();. That way the contents of doWhat will be evaluated to the object reference.
You can do something like
var doWhat = {}, str = "speak";
doWhat[str] = {
hello : function() {}
};
doWhat[str].hello();
jsName = 'PageIndexController';
//ST1
eval("if( typeof jsName === 'undefined')alert(111);");
//ST1
eval("if( typeof " + jsName + " === 'undefined')alert(222);");
//ST1 not work
//ST2 work and the output: 222;
//there are two different way using eval, we will get 2 different outcome.

Categories

Resources