根据值类型[数组或数字或字符串]对JSON对象进行排序

时间:2019-07-08 11:40:49

标签: javascript json sorting

我正在从服务器接收以下格式的JSON对象:

obj = {
    field1: "ONE",
    field2: "TWO",
    field3: [THREE1,THREE2,THREE3]
    field4: "FOUR",
    field5: [FIVE1,FIVE2,FIVE3]
};

即使我按顺序发送对象,即对象底部的数组和对象顶部的字符串,但我没有按有序形式接收。有什么办法可以按照以下格式对此进行排序。

obj = {
    field1: "ONE",
    field2: "TWO",
    field4: "FOUR",
    field3: [THREE1,THREE2,THREE3],
    field5: [FIVE1,FIVE2,FIVE3]
};

当前我正在使用以下方法,并且它可以正常工作,但是可能有更好的方法。

obj = {
    field1: "ONE",
    field2: "TWO",
    field3: [THREE1,THREE2,THREE3]
    field4: "FOUR",
    field5: [FIVE1,FIVE2,FIVE3]
};

var strObj = {};
var arrObj = {};

Object.keys(obj).forEach(function(key) {
  console.table("Key : " + key + ", Value : " + obj[key]);
  if (!(obj[key] instanceof Array)) {
    strObj[key] = obj[key];
  }
});
Object.keys(obj).forEach(function(key) {
  console.table("Key : " + key + ", Value : " + obj[key]);
  if (obj[key] instanceof Array) {
    arrObj[key] = obj[key];
  }
});

obj = { ...strObj, ...arrObj };
console.log(obj);`

1 个答案:

答案 0 :(得分:1)

您可以根据值是否为数组来sort对象的entries。然后使用Object.fromEntries()从排序的条目中创建一个新对象

const obj = {
  field1: "ONE",
  field2: "TWO",
  field3: ["THREE1", "THREE2", "THREE3"],
  field4: "FOUR",
  field5: ["FIVE1", "FIVE2", "FIVE3"]
};

const sortedEntries = Object.entries(obj)
                      .sort((a, b) => Array.isArray(a[1]) - Array.isArray(b[1]));
                      
const newObj = Object.fromEntries(sortedEntries)

console.log(newObj)