我正在谈论的API在一个非常奇怪的嵌套数组结构中返回它的注册表.我想将这个怪物转换成一个对象,这样我的应用程序就可以轻松访问存储在此输出中的整个对象.
API给我的输出看起来像这样:
[ [ "settings", "autoLogout", "false" ], [ "settings", "autoLogoutMinutes", "60" ], [ "settings", "presets", "true" ], [ "controller", "rs232", "ip", "192.168.1.11" ], [ "controller", "rs232", "name", "NX-22" ], [ "source", "M23836", "slot1", "ip", "192.168.1.30" ] ]
每个数组中的最后一个值表示条目的值,在最后一个条目之前的所有内容都与用于保存值的键相加.由于大小限制,我不能只在那里删除大的json编码对象,所以这不是一个可行的解决方法.
我现在做了一个非常肮脏和缓慢的解决方案,涉及2个eval().(我知道......这是一个禁忌,所以我正在寻找一个更好的解决方案)我猜这可以加载更快,但我无法弄清楚如何...
下面的代码段使用angular,因为我的应用程序是基于Angular的,但我对任何快速/干净的解决方案持开放态度.一个香草js方法或一些巧妙使用像lodash或下划线的东西将是非常受欢迎的.
我的肮脏和缓慢的解决方案
function DemoCtrl($scope){
$scope.data = [
[ "settings", "autoLogout", "false" ],
[ "settings", "autoLogoutMinutes", "60" ],
[ "settings", "presets", "true" ],
[ "controller", "rs232", "ip", "192.168.1.11" ],
[ "controller", "rs232", "name", "NX-22" ],
[ "source", "M23836", "slot1", "ip", "192.168.1.30" ]
]
$scope.init = function(){
var registry = {};
angular.forEach($scope.data, function(entry){
var keys = '';
entry.forEach(function(value, key, entry){
if( key != entry.length - 1 ){
//not last of array, so must be a key
keys += '[\'' + value + '\']';
// check if the object already exists
if( !angular.isDefined( eval('registry' + keys) ) ){
eval('registry' + keys + ' = {}');
}
}else{
//last one in this entry, must be the value
eval('registry' + keys + ' = \'' + value + '\'');
}
});
});
console.log('registry final');
console.log(registry);
$scope.registry = registry;
}
}
{{ registry | json }}