我有下面的JSON,它控制应用程序中页面的流向。要手动在屏幕之间导航,我使用页面的索引。如果要链接到Page 1,我将使用索引“ 0”。我希望能够使用id
进行导航。因此,我可以使用S010_010
进行导航。不幸的是,该应用程序的导航功能被多个元素使用,并且无法完全更改,因此我正在寻找一种可以获取ID并从flows
返回索引的方法。
var flows = {
"default": [{
theme: "theme1",
events: "touchstart",
easingSlideIn: "transition.fadeIn",
easingSlideOut: "transition.fadeOut",
easingRef: "transition.perspectiveRightIn",
easingPop: "transition.flipYIn"
},
{
id: "S010_010", //0
description: "",
chapter: "01",
ref: ""
},
{
id: "S020_010", //1
description: "",
chapter: "01",
ref: ""
},
{
id: "S030_010", //2
description: "",
chapter: "01",
ref: ""
},
]
};
这是我当前如何使用索引检索id
的示例:
this.options.flow[screen +1].id
答案 0 :(得分:1)
没有特定的方法,但是您可以创建自己的倒排索引
var invertedIndex = {};
flows.default.forEach((elem, index) => {
if(elem.id != null) {
invertedIndex[elem.id] = index - 1;
}
})
//then you can use the id for the lookup as
invertedIndex['S030_010']
答案 1 :(得分:1)
如果id与方法的匹配,则可以使用for-in进行迭代并返回索引。还建议使用for-of
,但是最终您会放弃使用类似for(const [index, value] of flows.default.entries())
的东西来获取索引,因此使用for-in
let flows = {
"default": [{
theme: "theme1",
events: "touchstart",
easingSlideIn: "transition.fadeIn",
easingSlideOut: "transition.fadeOut",
easingRef: "transition.perspectiveRightIn",
easingPop: "transition.flipYIn"
},
{
id: "S010_010", //0
description: "",
chapter: "01",
ref: ""
},
{
id: "S020_010", //1
description: "",
chapter: "01",
ref: ""
},
{
id: "S030_010", //2
description: "",
chapter: "01",
ref: ""
},
]
};
let getFlowByID = (id) => {
for(let eachFlowIndex in flows.default){
if(flows.default[eachFlowIndex].id == id){
return eachFlowIndex;
}
}
}
console.log(getFlowByID("S030_010")); // gets S030_010 index
答案 2 :(得分:0)
我们使用for in
循环来遍历对象数组,如果找到id,则返回索引。
ES5解决方案
var flows =
{
"default":
[
{
theme: "theme1",
events: "touchstart",
easingSlideIn: "transition.fadeIn",
easingSlideOut: "transition.fadeOut",
easingRef: "transition.perspectiveRightIn",
easingPop: "transition.flipYIn"
},
{
id: "S010_010", //0
description: "",
chapter: "01",
ref: ""
},
{
id: "S020_010", //1
description: "",
chapter: "01",
ref: ""
},
{
id: "S030_010", //2
description: "",
chapter: "01",
ref: ""
}
]
};
function getIndex(id)
{
var i = 0,
objs = flows.default;
for (i in objs)
if (objs[i].id == id)
return +i - 1
}
console.log(getIndex('S010_010')); //0
ES6解决方案
我们使用 Array.find
函数遍历数组,如果找到ID,则保存索引,然后返回索引。如果找不到,它将返回-1。但是不幸的是,该解决方案并不比我的ES5解决方案短。
var flows =
{
"default":
[
{
theme: "theme1",
events: "touchstart",
easingSlideIn: "transition.fadeIn",
easingSlideOut: "transition.fadeOut",
easingRef: "transition.perspectiveRightIn",
easingPop: "transition.flipYIn"
},
{
id: "S010_010", //0
description: "",
chapter: "01",
ref: ""
},
{
id: "S020_010", //1
description: "",
chapter: "01",
ref: ""
},
{
id: "S030_010", //2
description: "",
chapter: "01",
ref: ""
}
]
};
let getIndex = (id) => {
let ret = -1;
flows.default.find((elem, index) => {
if(elem.id == id)
ret = index - 1
});
return ret
};
console.log(getIndex('S010_010')); //0