简体   繁体   English

按字符串属性值对 JavaScript 对象进行排序

[英]Sort JavaScript object by string property value

Ok, so I'm getting some data from a server like this: myVar = JSON.parse(xhttp.responseText) .好的,所以我从这样的服务器获取一些数据: myVar = JSON.parse(xhttp.responseText) Now, my var looks something like:现在,我的 var 看起来像:

{
    someData1234:{
        score: "5",
        loc: "NY"
    },

    someData4321:{
        score: "70",
        loc: "MH"
    },

    someData4123:{
        score: "43",
        loc: "NG"
    }
}

How can i sort through the object so it orders it by the score in an descending order?如何对对象进行排序,使其按分数降序排列? i tried other solutions but didn't seem to work correctly as i need the same object(or an array of objects) back but just re-ordered我尝试了其他解决方案,但似乎无法正常工作,因为我需要返回相同的对象(或一组对象),但只是重新排序

As already noted, JavaScript object property order is not guaranteed , so you will have to convert your data into an array of objects and then sort.如前所述, JavaScript 对象的属性顺序是没有保证的,因此您必须将数据转换为对象数组,然后进行排序。 Following example uses Object.entries and map to convert the initial object into an array, then sorts by parsing a numerical value from score in each object:以下示例使用Object.entriesmap将初始对象转换为数组,然后通过解析每个对象中score的数值进行排序:

 const obj = { someData1234: { score: "5", loc: "NY" }, someData4321: { score: "70", loc: "MH" }, someData4123: { score: "43", loc: "NG" } }; const arr = Object.entries(obj).map(([k, v]) => ({[k]: v})); const sorted = arr.sort((a, b) => { return parseInt(a[Object.keys(a)[0]].score) - parseInt(b[Object.keys(b)[0]].score); }); console.log(sorted); // [{"someData1234":{"score":"5","loc":"NY"}},{"someData4123":{"score":"43","loc":"NG"}},{"someData4321":{"score":"70","loc":"MH"}}]

    var array = [{  
    "EmployeeName": "John",  
    "Experience": "12",  
    "Technology": "SharePoint"  
}, {  
    "EmployeeName": "Charles",  
    "Experience": "9",  
    "Technology": "ASP.NET"  
}, {  
    "EmployeeName": "Jo",  
    "Experience": "3",  
    "Technology": "JAVA"  
}, {  
    "EmployeeName": "Daine",  
    "Experience": "7",  
    "Technology": "Sql Server"  
}, {  
    "EmployeeName": "Zain",  
    "Experience": "6",  
    "Technology": "C#"  
}];  
//Comparer Function  
function GetSortOrder(prop) {  
    return function(a, b) {  
        if (a[prop] > b[prop]) {  
            return 1;  
        } else if (a[prop] < b[prop]) {  
            return -1;  
        }  
        return 0;  
    }  
}  

array.sort(GetSortOrder("EmployeeName")); //Pass the attribute to be sorted on  
document.write("Sorted Employee Names : ");  
for (var item in array) {  
    document.write("<br>" + array[item].EmployeeName);  
}  

array.sort(GetSortOrder("Technology")); //Pass the attribute to be sorted on  
document.write("<br><br> Sorted Technology Names : ");  
for (var item in array) {  
    document.write("<br>" + array[item].Technology);  
}  
  let something = {
    someData1234: {
      score: "5",
      loc: "NY"
    },

    someData4321: {
      score: "70",
      loc: "MH"
    },

    someData4123: {
      score: "43",
      loc: "NG"
    }
  };
  let someArray = [];
  let myArray = []
  Object.keys(something).map((som, ind) => {
    myArray.push(`${Object.values(Object.entries(something)[ind][1])[0]}` + ind);
  });
  myArray.sort((a, b) => {
    return a - b
  });
  console.log(myArray);

  for (let i = 0; i < myArray.length; i++) {
      let obj=Object.entries(something)[myArray[i].charAt(myArray[i].length-1)];
      console.log(obj);
      let key= obj[0];
      let value=obj[1];
    someArray.push({[key]:value})
  }
  let myOrderedObject;
  let obj;
  for(let i=0;i<someArray.length;i++){
     obj=someArray[i];
    console.log(obj);
     myOrderedObject={...myOrderedObject,...obj};
     console.log(myOrderedObject);
    console.log(i);
  }
  console.log('mY ordered Object ',myOrderedObject);

  console.log(someArray);

Hope it helps...希望能帮助到你...

You could move the keys (like "someData1234") inside the objects (as the value of a "key" property), and put those objects in an array sorted by your liking: that way you have all information at hand:您可以移动对象内的键(如“someData1234”)(作为“键”属性的值),并将这些对象放入按您喜好排序的数组中:这样您就拥有了所有信息:

 const data = {someData1234:{score: "5",loc: "NY"},someData4321:{score: "70",loc: "MH"},someData4123:{score: "43",loc: "NG"}}; const result = Object.entries(data).map(([key, val]) => ({key, ...val})) .sort((a,b) => a.score - b.score); console.log(result);

 const data = { someData1234:{ score: "5", loc: "NY" }, someData4321:{ score: "70", loc: "MH" }, someData4123:{ score: "43", loc: "NG" } }; // Use an Intl.Collator to construct a function that will sort number strings const naturalSort = new Intl.Collator(undefined, { numeric: true }).compare; const sortProperties = obj => Object.getOwnPropertyNames(obj) // Get the list of properties .sort((a, b) => naturalSort(obj[a].score, obj[b].score)) // Order based on the score .reduce( // Reduce the ordered properties to create a new object (result, prop) => { result[prop] = obj[prop]; return result; }, {} ); console.log(sortProperties(data));

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

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