嘿伙计们我在这个问题上遇到了一些麻烦,我希望有人可以帮助我。我正在尝试将遵循此格式foo.bar::baz
的字符串拆分为类似于此foo.bar.baz = ''
的对象
在PHP中,我将使用以下
执行此操作 $obj = New stdClass();
$inp = [
'type1',
'type2',
'type3.sub1::blah1',
'type3.sub2::blah1',
'type4.sub1::blah2',
'type4.sub2::blah2',
'type5.sub1',
];
foreach ($inp AS $v)
{
if (strpos($v, '.'))
{
$b = explode('.', $v);
$obj->$b[0] = '';
if (strpos($b[1], '::') && $c = explode('::', $b[1]))
{
$obj->$b[0]->$c[0]->$c[1] = '';
} else {
$obj->$b[0]->$b[1] = '';
}
} else {
$obj->$v = '';
}
}
print_r($obj);
stdClass Object
(
[type1] =>
[type2] =>
[type3] => stdClass Object
(
[sub2] => stdClass Object
(
[blah1] =>
)
)
[type4] => stdClass Object
(
[sub2] => stdClass Object
(
[blah2] =>
)
)
[type5] => stdClass Object
(
[sub1] =>
)
)
我目前正试图在Javascript中模仿这样做,但是似乎无法让它表现出来
var fieldset = results.fooresult.metadata[0].field;
var namespace = [];
// namespace from meta
for (var k in fieldset) {
if (fieldset.hasOwnProperty(k)) {
var string = fieldset[k]['$']['NAME'];
if (0<string.indexOf('.')) {
var pairs = string.split('.');
if (0<pairs[1].indexOf('::')) {
var value = pairs[1].split("::");
namespace[pairs[0]][value[0]] = value[1];
} else {
namespace[pairs[0]] = pairs[1];
}
} else {
namespace.push(string);
}
}
}
帮助将不胜感激
答案 0 :(得分:1)
这应该有效:
var inp = [
'type1',
'type2',
'type3.sub1::blah1',
'type3.sub2::blah1',
'type4.sub1::blah2',
'type4.sub2::blah2',
'type5.sub1'
];
function makeTree(inp) {
var result = {};
var split = inp.map(function (str) {
return str.split(/\.|::/);
});
var walk = function (obj, propList) {
if (propList.length == 1) {
obj[propList[0]] = '';
return;
}
var nextObj = obj[propList[0]] = obj[propList[0]] || {};
propList.shift();
walk(nextObj, propList);
};
split.forEach(walk.bind(null, result));
return result;
}
var out = makeTree(inp);