JS array string patch name for array (object)
I am having problems with js array. I have a patch name (string) similar to "user.joey.friends.0.franc") and I need to "compress" to look like this:
console.log( parseArray( "user.joey.friends.0.franc" ) );
//Object {
user: {
joey: {
friends: {
0: {
franc: 1
}
}
}
}
}
Any ideas how to do this?
0
source to share
3 answers
If you say that you have an object with the structure you specified and you are trying to find a property defined by your string "user.joey.friends.0.franc"
, this is a pretty simple loop: Live example
function findProperty(obj, path) {
var steps = path.split(/\./);
var step;
var n;
for (n = 0; n < steps.length; ++n) {
step = steps[n];
if (!(step in obj)) {
return undefined;
}
obj = obj[step];
}
return obj;
}
var a = {
user: {
joey: {
friends: {
0: {
franc: 1
}
}
}
}
};
console.log(findProperty(a, "user.joey.friends.0.franc")); // "1"
0
source to share
If you are trying to create an object from a string, this solution is what I am currently using until I find something better (I believe this is based on Yahoo's namespacing method):
function createObject() {
var a = arguments, i, j, d, _this;
var out = {};
for (i = 0; i < a.length; i = i + 1) {
d = a[i].split('.');
out2 = out;
for (j = 0; j < d.length; j = j + 1) {
out2[d[j]] = out2[d[j]] || {};
out2 = out2[d[j]];
}
}
return out;
}
createObject('user.joey.friends.0.franc');
0
source to share