如何在JavaScript中将像这样的字符串""0.children.13.children.0"
解析到数组项的路径?
示例:"0.children.13.children.0"
> arr[0].children[13].children[0]
预先感谢!
答案 0 :(得分:0)
如果对象的键中有点,如.
,则使用一个字符串在{'first.name':'John'}
上分割可能会损坏,因此最好为数组提供字符串/整数。
这是lodash get的一种实现,不同之处在于它只将path作为字符串:
var data = [
{
children: [
{
children: [{ name: 'got it' }],
},
],
},
null,
];
const get = (object, path = '', defaultValue) => {
const recur = (object, path, defaultValue) => {
if (typeof object !== 'object') {
return defaultValue;
}
if (path.length === 0) {
return object;
}
if (object !== null && path[0] in object) {
return recur(
object[path[0]],
path.slice(1),
defaultValue,
);
}
return defaultValue;
};
return recur(object, path.split('.'), defaultValue);
};
console.log(get(undefined, '', 'Hello World'));//defaults to hello world
console.log(get(data, 'does.not.exist', 'Hello World'));//defaults to hello world
console.log(get(data, '1', 'Hello World'));//will be null (data[0] is null)
console.log(get(data, '1.anything', 'Hello World'));//defaults to hello world
console.log(//gets item data[0].children[0].children[0]
get(data, '0.children.0.children.0', 'Hello World'),
);