简体   繁体   中英

JSON array sort by key value

I want to sort aa json array by selected key value.

    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. expected json I want like this

 {
        "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?

You can do what you want with 4 steps:

  • filter on whether distance is null
  • sort 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 ))
  • map to the post_id
  • join with ,

 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:

.filter(({ distance }) => distance)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM