给出路径“documents / settings / user”
如何将其作为嵌套对象
结果
SELECT main.*
FROM
(
SELECT
CASE WHEN On_The_Table.Backpack_Number IS NOT NULL THEN On_The_Table.Backpack_Number ELSE Logs.Backpack_Number END AS Backpack_Number
, On_The_Table.Pokemon_Number
, On_The_Table.Name
, On_The_Table.DateCaught
, ROW_NUMBER() OVER() AS RANK
FROM On_The_Table
LEFT JOIN
(
SELECT DISTINCT
Backpack_Number,
Pokemon_Number,
DateCaught
FROM What_We_Wrote_Down
WHERE Backpack_Number IS NOT NULL AND Action = 'Caught'
) Logs
ON On_The_Table.Pokemon_Number = Logs.Pokemon_Number AND On_The_Table.Date_Caught = Logs.Date_Caught
) main
WHERE RANK >= @searchParm1 AND RANK <= @searchParm2
我想不出如何引用每个先前的路径
{
documents : {
settings : {
user : {}
}
}
}
答案 0 :(得分:2)
使用.reduce()
实际上很容易做到这一点。
var dir = {}
var paths = "documents/settings/user".split('/')
paths.reduce(function(dir, path) {
return dir[path] = {}
}, dir)
console.log(dir)
&#13;
因为第一个参数始终是返回的最后一个值(或提供的第一个值),所以我们需要做的就是返回分配给当前路径的对象。并且因为赋值导致赋值,我们可以将其用作return
语句本身的表达式。
如果需要,您可以防止由于相邻分隔符而导致的空路径名称。
var dir = {}
var paths = "documents///settings/user".split('/')
paths.reduce(function(dir, path) {
return path ? (dir[path] = {}) : dir
}, dir)
console.log(dir)
&#13;
答案 1 :(得分:1)
Object
通过引用传递。您可以使用此功能并执行此类操作。
var paths = "documents/settings/user".split('/')
var r = {};
var _tmp = r;
paths.forEach(function(el){
_tmp[el] = {};
_tmp = _tmp[el];
});
console.log(r)
&#13;
var paths = "documents/settings/user".split('/')
var r = {};
var _tmp = r;
for(var i=0; i<paths.length; i++){
_tmp = (_tmp[paths[i]] = {});
};
console.log(r)
&#13;
答案 2 :(得分:0)
另一种优雅的解决方案来构建具有价值的对象:
const buildObjWithValue = (path, value = '') => {
const paths = path.split('.');
return paths.reduceRight((acc, item, index) => ({
[item]: index === paths.length - 1
? value
: acc
}), {});
}
例如 buildObjWithValue('very.deep.lake', 'Baikal')
给我们
{
very: {
deep: {
lake: 'Bailkal'
}
}
}