gpt4 book ai didi

JavaScript - 按嵌套值对 JSON 对象进行排序

转载 作者:行者123 更新时间:2023-11-30 12:03:00 24 4
gpt4 key购买 nike

总结:有一个多层次的亲子评论系统,即

示例:

comment 1
comment 1-1
comment 1-1-1
comment 1-2
comment 1-2-1
comment 1-2-2

这里,comment 1 是父级,comment 1-1 & comment 1-2 都是 comment 1 的子项,依此类推。

要求:

我们希望根据属性值实现对整个对象的排序。即时间戳(最新的评论或回复会出现在最上面)。

JSON 对象:

{
"CommentText": "",
"CommentCreateStamp": "2016-03-22",
"Comments": [{
"CommentText": "comment 1",
"CommentCreateStamp": "2016-03-09",
"Comments": [{
"CommentText": "comment 1-1",
"CommentCreateStamp": "2016-03-15",
"Comments": [{
"CommentText": "comment 1-1-1",
"CommentCreateStamp": "2016-03-21",
"Comments": null
}]
}]
}],
"Comments": [{
"CommentText": "comment 2",
"CommentCreateStamp": "2016-03-12",
"Comments": [{
"CommentText": "comment 2-1",
"CommentCreateStamp": "2016-03-10",
"Comments": [{
"CommentText": "comment 2-1-1",
"CommentCreateStamp": "2016-03-14",
"Comments": null
}]
}]
}]
}

到目前为止我试过了:

JSfiddle:https://jsfiddle.net/asceeevb/

我在 Stack Overflow 上看到很多问题,但没有按要求工作。

最佳答案

我不完全确定你在问什么,但你的代码有几处似乎有问题:

  • 您重新定义了对象的 comments 属性,也许您想要一个数组?
  • 您的排序函数应该根据元素的比较返回一个值,而不是输出它。参见 this SO question用于日期比较。

更新:您很接近,您缺少的是对嵌套评论的 sorting 的调用。下面是递归调用 sorting 的片段:

var people = {
"CommentText": "",
"CommentCreateStamp": "",
"Comments": [{
"CommentText": "c1",
"CommentCreateStamp": "2016-03-23 06:05:36",
"Comments": [{
"CommentText": "c2",
"CommentCreateStamp": "2016-03-23 06:05:59",
}],
}, {
"CommentText": "a1",
"CommentCreateStamp": "2017-03-23 06:05:45",
"Comments": [{
"CommentText": "a2",
"CommentCreateStamp": "2016-03-23 06:06:05",
}, {
"CommentText": "a3",
"CommentCreateStamp": "2016-03-23 06:06:16",
}, {
"CommentText": "a4",
"CommentCreateStamp": "2016-03-23 06:06:23",
}],
}],
};



function sorting(js_object, key_to_sort_by) {

function sortByKey(a, b) {
var x = a[key_to_sort_by];
var y = b[key_to_sort_by];
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
};

js_object.sort(sortByKey);

};

function sortComments(comments) {

sorting(comments, 'CommentCreateStamp');
for (var i = 0; i < comments.length; i++)
if (comments[i].hasOwnProperty('Comments'))
sortComments(comments[i].Comments);

};

sortComments(people.Comments);
console.log(people.Comments);

关于JavaScript - 按嵌套值对 JSON 对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36160456/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com