我正在寻找一种方法来将javascript移动元素中的数组重新排序到特定位置。
我的数组是:
[
{
"id": 105142,
"parent": null,
"created": "2015-03-20T17:21:33.013+01:00"
},
{
"id": 105150,
"parent": null,
"created": "2015-03-20T19:02:09.079+01:00"
},
{
"id": 105160,
"parent": null,
"created": "2015-03-20T22:15:06.543+01:00"
},
{
"id": 105190,
"parent": null,
"created": "2015-03-21T19:39:19.441+01:00"
},
{
"id": 105193,
"parent": null,
"created": "2015-03-22T01:42:00.974+01:00"
},
{
"id": 105195,
"parent": 105193,
"created": "2015-03-22T11:05:20.033+01:00"
},
{
"id": 105197,
"parent": null,
"created": "2015-03-22T11:06:15.241+01:00"
},
{
"id": 105203,
"parent": 105193,
"created": "2015-03-22T22:22:48.833+01:00"
}
]
我必须在父项下移动父项!== null的项目。 结果将是:
[
{
"id": 105142,
"parent": null,
"created": "2015-03-20T17:21:33.013+01:00"
},
{
"id": 105160,
"parent": 105142,
"created": "2015-03-20T22:15:06.543+01:00"
},
{
"id": 105150,
"parent": null,
"created": "2015-03-20T19:02:09.079+01:00"
},
{
"id": 105190,
"parent": null,
"created": "2015-03-21T19:39:19.441+01:00"
},
{
"id": 105193,
"parent": null,
"created": "2015-03-22T01:42:00.974+01:00"
},
{
"id": 105195,
"parent": 105193,
"created": "2015-03-22T11:05:20.033+01:00"
},
{
"id": 105203,
"parent": 105193,
"created": "2015-03-22T22:22:48.833+01:00"
},
{
"id": 105197,
"parent": null,
"created": "2015-03-22T11:06:15.241+01:00"
}
]
是否有任何js库可以在没有大量递归的情况下有效地移动项目?
答案 0 :(得分:1)
使用Array.prototype.sort
应该是个好主意。唯一棘手的事情是比较的关键。这里,子节点应该大于它的父节点;子项及其父项应该比其他节点更大或更小。因此,通过自身及其父母的钥匙来比较钥匙。以下代码显示了如何执行此操作:
var re = {};
for (var i = 0, l = a.length; i < l; i++) re[a[i].id] = a[i];
var id = function (x) {
var r = [x];
for (; x; x = re[x].parent) {
r.unshift(x);
}
return r.join('-');
};
a.sort(function (x, y) {
if (x === y) return 0;
if (id(x.id) > id(y.id)) return 1; else return -1;
});
此处,a
是数组。
答案 1 :(得分:0)
我认为你不需要图书馆:
Ckeck数组操作here并检查splice()
强大的splice()方法允许您从数组中的任何点添加和/或删除一个或多个元素:
你只需找到对象,存储它,从数组中删除并插入新位置。
答案 2 :(得分:0)
不需要递归,两个嵌套循环将执行:
data = [
{
"id": 105142,
"parent": null,
"created": "2015-03-20T17:21:33.013+01:00"
},
{
"id": 105150,
"parent": null,
"created": "2015-03-20T19:02:09.079+01:00"
},
{
"id": 105160,
"parent": null,
"created": "2015-03-20T22:15:06.543+01:00"
},
{
"id": 105190,
"parent": null,
"created": "2015-03-21T19:39:19.441+01:00"
},
{
"id": 105193,
"parent": null,
"created": "2015-03-22T01:42:00.974+01:00"
},
{
"id": 105195,
"parent": 105193,
"created": "2015-03-22T11:05:20.033+01:00"
},
{
"id": 105197,
"parent": null,
"created": "2015-03-22T11:06:15.241+01:00"
},
{
"id": 105203,
"parent": 105193,
"created": "2015-03-22T22:22:48.833+01:00"
}
]
result = [];
data.forEach(function(x) {
if(!x.parent) {
result.push(x);
data.forEach(function(y) {
if(y.parent == x.id)
result.push(y)
})
}
})
document.write("<pre>" + JSON.stringify(result,0,3));
这是“二次”的,但除非你有数百万个元素,否则它会正常工作。