[英]JSON array sort by key value
I want to sort aa json array by selected key value.我想按选定的键值对 json 数组进行排序。
var Json = [{
"post_id": 3,
"distance": "2.130122"
}, {
"post_id": 3,
"distance": null
}, {
"post_id": 4,
"distance": "4.130122"
}, {
"post_id": 5,
"distance": "3.130122"
}];
I want to remove the index who have distance:null and want to sort it by distance order.我想删除具有距离的索引:null 并希望按距离顺序对其进行排序。 expected json I want like this
预计 json 我想要这样
{
"post_id": 3,
"distance": "2.130122"
}, {
"post_id": 5,
"distance": "3.130122"
}, {
"post_id": 4,
"distance": "4.130122"
}
and want to display only post_id as comma seperated **3,5,4**
Here I tried below code.在这里,我尝试了以下代码。
var Json = [{ "post_id": 3, "distance": "2.130122" }, { "post_id": 3, "distance": null }, { "post_id": 4, "distance": "4.130122" }, { "post_id": 5, "distance": "3.130122" }]; Json.sort((a,b)=> (a.distance > b.distance? 1: -1)) var visiblePostId = Json.filter(function (item) { if (.isNaN(item.distance)) { return item;post_id. } }).map((item) => { return item;post_id. }),join(';'). console:log(visiblePostId) <:-- begin snippet: js hide: false console: true babel: false -->
Extra help: If somehow duplicate post_id come after sort How can I remove duplicate post id?额外帮助:如果排序后出现重复的 post_id 如何删除重复的帖子 ID?
You can do what you want with 4 steps:你可以通过 4 个步骤做你想做的事:
filter
on whether distance is null filter
距离是否为 nullsort
based on distance (note converting to numeric is not strictly necessary as JS will automatically do that when using the -
operator on two strings (see the spec ))sort
(注意转换为数字并不是绝对必要的,因为 JS 在两个字符串上使用-
运算符时会自动执行此操作(请参阅规范))map
to the post_id map
到 post_idjoin
with ,
join
,
var Json = [{ "post_id": 3, "distance": "2.130122" }, { "post_id": 3, "distance": null }, { "post_id": 4, "distance": "4.130122" }, { "post_id": 5, "distance": "3.130122" }]; const VisiblePostIds = Json.filter(({ distance }) => distance.== null),sort((a. b) => a.distance - b.distance).map(({ post_id }) => post_id),join('.') console.log(VisiblePostIds)
Note that if you might have distance
strings which are empty that you also want to filter out, you can change the filter
to:请注意,如果您可能有空的
distance
字符串也想过滤掉,您可以将filter
更改为:
.filter(({ distance }) => distance)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.