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

时间:2019-03-12 04:17:44

标签: javascript sorting javascript-objects

好吧,所以我从这样的服务器上获取了一些数据:myVar = JSON.parse(xhttp.responseText)。现在,我的var看起来像:

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

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

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

我该如何对对象进行排序,使其按分数降序排列?我尝试了其他解决方案,但似乎无法正常工作,因为我需要返回相同的对象(或对象数组),但只​​是重新排序

5 个答案:

答案 0 :(得分:1)

如前所述,JavaScript object property order is not guaranteed,因此您必须将数据转换为对象数组,然后进行排序。以下示例使用Object.entriesmap将初始对象转换为数组,然后通过解析每个对象中score的数值进行排序:

const obj = {
  someData1234: {score: "5", loc: "NY"},
  someData4321: {score: "70", loc: "MH"},
  someData4123: {score: "43", loc: "NG"}
};

let arr = Object.entries(obj).map(([k, v]) => ({[k]: v}));
let 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"}}]

答案 1 :(得分:0)

    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);  
}  

答案 2 :(得分:0)

  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);

希望有帮助...

答案 3 :(得分:0)

您可以将键(例如“ someData1234”)移动到对象内部(作为“ key”属性的值),然后将这些对象放入按您的喜好排序的数组中:这样您就可以掌握所有信息:

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);

答案 4 :(得分:-3)

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));