问题
i have trouble with js array. I have patch name(string) look like ( "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 that ?
回答1:
Here's a non recursive way to get you most of the way there.
function compress(str) {
var split = str.split('.'), obj = {}, current = obj, i;
for (i = 0; i < split.length; i++){
current[split[i]] = {} ;
current = current[split[i]];
}
return obj;
}
回答2:
If you're saying you have an object with the structure you've quoted, and you're trying to look up the property defined by your string "user.joey.friends.0.franc"
, that's a fairly straightforward 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"
回答3:
If you're trying to create an object from a string, this solution is what I currently use until I find something better (I believe it based on a namespacing method from Yahoo):
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');
DEMO
来源:https://stackoverflow.com/questions/25510551/js-array-string-patch-name-to-arrayobject