简体   繁体   English

按字母顺序对 JavaScript 中的特定(键->值)排序整个 object?

[英]sort whole object with specific (key->value) in JavaScript alphabetically?

I have an array in JavaScript that looks like我在 JavaScript 中有一个数组,看起来像

[
   {
      "name":"a",
      "phoneNo":"1"
   },
   {
      "name":"X",
      "phoneNo":"3"
   },
   {
      "name":"A",
      "phoneNo":"2"
   },
   {
      "name":"b",
      "phoneNo":"4"
   },
   {
      "name":"c",
      "phoneNo":"5"
   },
   {
      "name":"D",
      "phoneNo":"6"
   }
]

and I want to sort it by the name value in each array, alphabetically.我想按每个数组中的名称值按字母顺序对其进行排序。 NOTE: all name will be converted to lowercase first.注意:所有名称将首先转换为小写。 I am stuck with this problem and I tried alot to solve it myself and also tried some research but I did'nt found something.我被这个问题困住了,我自己尝试了很多方法来解决它,也尝试了一些研究,但我没有找到任何东西。 Help!!!帮助!!!

Using lodash, you can easily solve the problem: use Lodash to sort array of object by value使用lodash可以轻松解决问题: 使用Lodash对object的数组按值排序

_.sortBy(myArray, o => o.name.toLowerCase())

Solution using JS使用JS的解决方案

Reference here参考这里

 const arr = [ { "name":"a", "phoneNo":"1" }, { "name":"X", "phoneNo":"3" }, { "name":"A", "phoneNo":"2" }, { "name":"b", "phoneNo":"4" }, { "name":"c", "phoneNo":"5" }, { "name":"D", "phoneNo":"6" } ] console.log(arr.sort(function(a, b){ var nameA=a.name.toLowerCase(), nameB=b.name.toLowerCase(); if (nameA < nameB) //sort string ascending return -1; if (nameA > nameB) return 1; return 0; //default return value (no sorting) }));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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