给出the object的简单方法是从给定路径以字符串导航到正确的深层对象吗?
示例路径:
[
"campaigns.0.name",
"campaigns.0.segments.0.name",
"campaigns.0.segments.0.dimensions.0.category",
"campaigns.0.segments.1.metrics.0.category",
"campaigns.1.segments.14.filters.1.expression"
]
如果我以“手动”方式进行操作,则为:
var s = path[2].split('.'); // campaigns.0.segments.0.dimensions.0.category
originalObject[s[0]][s[1]][s[2]][s[3]][s[4]];
我确实得到了正确的输出...但是我以编程方式来完成它?
我尝试了替换:
var newPath = path;
for(i = 0; i < path.match(/\./g).length; i++) {
if(i%2===0) newPath = newPath.replace('.', '[');
else newPath = newPath.replace('.', ']'); }
newPath = newPath.replace(/]/g, '].');
"campaigns[1].segments[14].filters[1].expression"
但originalObject[output]
不会
然后我想我可以简单地从对象中删除属性,例如:
var splitPath = path[2].split('.'); // campaigns.0.segments.0.dimensions.0.category
var newPath = originalObject; // start with the full object
// -1 so we end up in the object and not the property
for(i = 0; i < splitPath.length-1; i++) {
newPath = newPath[splitPath[i]]; } // navigate through the object
console.log(newPath);
然后我按预期到达了所需对象
{
"id":10929,
"dimension":"ga:eventAction",
"operator":"IN_LIST",
"expression":"Cart - Cyenter - Create Account",
"exclude":0
}
我只是想知道在像这样的给定路径中导航时,是否有更简单的方法到JSON对象...