我有一个这样的数组:
[{Object_id: "000", label: "Avertissement"},{Object_id: "001",label: "Chapitre 1",entry: [{Object_id: "001/003",label: "Chapitre 1-1"},{Object_id: "001/004",label: "Chapitre 1-2",entry: [{Object_id: "001/004/001",label: "Chapitre 1-2-1"},{Object_id: "001/004/002",label: "Chapitre 1-2-2"}]}]}];
我想找到所有父项的Object Id,提供Object_id项 因此,如果我给函数赋值“001/004/002”,它返回[“001”,“001/003”],我的意思是,父母的所有id的数组(如面包屑)。阵列数组最多可以有五个级别。
我更喜欢基于下划线的解决方案,但纯JS或jquery都可以。
答案 0 :(得分:1)
看起来Nina只是打败了我!无论如何,这是我的解决方案。它还使用递归来查找您要求的确切项目,但会跟踪它所经历的层次结构。
var o = [{
Object_id: "000",
label: "Avertissement"
}, {
Object_id: "001",
label: "Chapitre 1",
entry: [{
Object_id: "001/003",
label: "Chapitre 1-1"
}, {
Object_id: "001/004",
label: "Chapitre 1-2",
entry: [{
Object_id: "001/004/001",
label: "Chapitre 1-2-1"
}, {
Object_id: "001/004/002",
label: "Chapitre 1-2-2"
}]
}]
}];
var getParentIds = function(id, o, hierarchy) {
var find = function(id, o) {
for (var i = 0; i < o.length; ++i) {
var ob = o[i];
if (ob['Object_id'] == id) {
return ob;
} else {
if (ob['entry'] != null) {
hierarchy.push(ob);
return find(id, ob['entry']);
}
}
}
};
var theObject = find(id, o, []);
for (var i = 0; i < hierarchy.length; ++i) {
document.write(hierarchy[i]['Object_id'] + '<br/>');
}
};
getParentIds('001/004/002', o, []);
答案 1 :(得分:1)
因为你的id已经包含了路径,为什么不使用它呢?
function parentIds(id){
for(var out = [], i = id.indexOf("/"); i > -1; i = id.indexOf("/", i+1))
out.push(id.substr(0, index));
return out;
}
parentIds("001/004/001")
否则
function parentIds(id, data){
var result = [];
function traverse(node){
if(node){
//if(node instanceof Array) return node.some(traverse); //ES6
if(node instanceof Array) return _.some(node, traverse); //underscore
if(node.Object_id === id) return true;
if(traverse(node.entry)){
result.push(node.Object_id);
return true;
}
}
return false;
}
traverse(data);
return result;
}
答案 2 :(得分:0)
此提案使用iter()
的递归调用获取给定字符串的所有父项。
var data = [{ Object_id: "000", label: "Avertissement" }, { Object_id: "001", label: "Chapitre 1", entry: [{ "Object_id": "001/003", "label": "Chapitre 1-1" }, { "Object_id": "001/004", "label": "Chapitre 1-2", entry: [{ "Object_id": "001/004/001", "label": "Chapitre 1-2-1" }, { "Object_id": "001/004/002", "label": "Chapitre 1-2-2" }] }] }],
result = getParentId("001/004/002", data);
function getParentId(id, data) {
function iter(id, data, level) {
var key = id.split('/').filter(function (_, i) { return i <= level; }).join('/'),
result = [];
data.some(function (a) {
if (a.Object_id === key) {
result.push(a.Object_id);
if (id !== key && Array.isArray(a.entry)) {
result = result.concat(iter(id, a.entry, level + 1));
}
return true;
}
});
return result;
}
return iter(id.substring(0, id.lastIndexOf('/')), data, 0);
}
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');