在数组中按数组排序对象?

时间:2021-01-17 15:53:12

I have a local storage that looks like this:

我有一个本地存储,看起来像这样:

Key: Savedme        
Value:
{
 "Bob":["1","1"],
 "John":["2","1"],
 "Mom":["3","1"],
 "Dad":["1","2"],
 "Tom":["3","2"],
 "Skipper42":["2","3"],
 "Hated_41":["3","3"],
 "Greeneggs":["2","2"],
 "William":["1","3"]
}

I need to somehow sort it to look like this

我需要以某种方式将它排序为这样

{
 "Bob":["1","1"],
 "Dad":["1","2"],
 "William":["1","3"]
 "John":["2","1"],
 "Greeneggs":["2","2"],
 "Skipper42":["2","3"],
 "Mom":["3","1"],
 "Tom":["3","2"],
 "Hated_41":["3","3"]
}

I've tried storing it in a matrix such as this:

我已经尝试将它存储在如下的矩阵中:

var $runthrough = [[]];
$runthrough[$x,$y] = $values;

Where x is the first set of numbers, y is the next and then values is Bob, Dad etc...from there I could just do a foreach for both sections of the matrix and it would be done, HOWEVER when I use this method after it runs through one set of the objects, the second set gives an "undefined" even though I have setup some triggers to check and it's not actually going undefined.

其中x是第一组数字,y是下一个,然后值是Bob,Dad等......从那里我可以为矩阵的两个部分做一个foreach并且它会完成,但是当我使用这个方法时在它运行一组对象之后,第二组给出了“未定义”,即使我已经设置了一些触发器来检查它并且它实际上并没有未定义。

var loadarray = JSON.parse(localStorage.getItem( 'savedme' ));
$.each(loadarray, function(k, v) {
     if(typeof k === 'undefined' || !k){
        console.error("undefined found at k!");
    };
     if(typeof v[0] === 'undefined' || !v[0]){
        console.error("undefined found at x!");
    };
     if(typeof v[1] === 'undefined' || !v[1]){
         console.error("undefined found at y!");
    };
});

so I've come to realize, I'm probably doing something wrong with arrays so I figured it would be faster to sort out the array and THEN use the same function. It HAS to be ordered like this because it's basically going to be outputted to a matrix table, I tried ordering it like this:

所以我已经意识到,我可能在做错了数组,所以我认为排序数组会更快,然后使用相同的函数。它有这样的顺序,因为它基本上将被输出到矩阵表,我尝试这样排序:

  {
    "1":["1","Bob"],
    "2":["1","John"],
  } 

but...the index value 1 would just be overwritten by the last value

但是...索引值1只会被最后一个值覆盖

3 个解决方案

#1


2  

Objects properties do not have a guaranteed order in JavaScript, you need to use an Array.

对象属性在JavaScript中没有保证顺序,您需要使用数组。

Definition of an Object from ECMAScript Third Edition (pdf):

ECMAScript第三版中对象的定义(pdf):

4.3.3 Object
An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.

4.3.3对象对象是Object类型的成员。它是一个无序的属性集合,每个属性都包含一个原始值,对象或函数。存储在对象属性中的函数称为方法。

Try a data structure like this instead:

尝试这样的数据结构:

[
 { name: "Bob", value: ["1","1"] },
 { name: "Dad", value: ["1","2"] },
 { name: "William", value: ["1","3"] },
 { name: "John", value: ["2","1"] },
 { name: "Greeneggs", value: ["2","2"] },
 { name: "Skipper42", value: ["2","3"] },
 { name: "Mom", value: ["3","1"] },
 { name: "Tom", value: ["3","2"] },
 { name: "Hated_41", value: ["3","3"] }
]

You can generate this structure like this:

您可以像这样生成此结构:

var loadarray = JSON.parse(localStorage.getItem( 'savedme' ));
var sorted = [];
for (var prop in loadarray) {
    if (loadarray.hasOwnProperty(prop)) {
        sorted.push({name:prop, value:loadarray[prop]});
    }
}
sorted.sort(function(a, b) {
    var v0 = a.value[0] - b.value[0];
    return v0 == 0 ? a.value[0] - a.value[0] : v0;
});

#2


2  

var a = [
  { "Bob": ["1", "1"] },
  { "John": ["2", "1"] },
  { "Mom": ["3", "1"] },
  { "Dad": ["1", "2"] },
  { "Tom": ["3", "2"] },
  { "Skipper42": ["2", "3"] },
  { "Hated_41": ["3", "3"] },
  { "Greeneggs": ["2", "2"] },
  { "William": ["1", "3"] }
];

a.sort(function (a, b) {
  var aa = a[Object.keys(a)],
      bb = b[Object.keys(b)];
  if (aa[0] === bb[0]) {
    return aa[1] - bb[1];
  } else {
    return aa[0] - bb[0];
  }
});
document.querySelector("#demo").innerHTML = JSON.stringify(a, null, 4);
<div id="demo"></div>

#3


0  

Keys cannot be sorted within an object.

密钥无法在对象中排序。

However, they can be processed in order using Object.keys(object).sort().

但是,可以使用Object.keys(object).sort()按顺序处理它们。

Here, I'm outputting the object to an array – sorted by the keys' values – then displaying that array:

在这里,我将对象输出到一个数组 - 按键的值排序 - 然后显示该数组:

var obj= {
 "Bob":["1","1"],
 "John":["2","1"],
 "Mom":["3","1"],
 "Dad":["1","2"],
 "Tom":["3","2"],
 "Skipper42":["2","3"],
 "Hated_41":["3","3"],
 "Greeneggs":["2","2"],
 "William":["1","3"]
}

var arr= Object.keys(obj)
          .sort(function(a, b) {
            if(obj[a][0]===obj[b][0]) {
              return obj[a][1] - obj[b][1];
            }
            else {
              return obj[a][0] - obj[b][0];
            }
          })
          .map(function(key) {
            var o= {};
            o[key]= obj[key];
            return o;
          });

document.body.innerHTML= JSON.stringify(arr);

#1


2  

Objects properties do not have a guaranteed order in JavaScript, you need to use an Array.

对象属性在JavaScript中没有保证顺序,您需要使用数组。

Definition of an Object from ECMAScript Third Edition (pdf):

ECMAScript第三版中对象的定义(pdf):

4.3.3 Object
An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.

4.3.3对象对象是Object类型的成员。它是一个无序的属性集合,每个属性都包含一个原始值,对象或函数。存储在对象属性中的函数称为方法。

Try a data structure like this instead:

尝试这样的数据结构:

[
 { name: "Bob", value: ["1","1"] },
 { name: "Dad", value: ["1","2"] },
 { name: "William", value: ["1","3"] },
 { name: "John", value: ["2","1"] },
 { name: "Greeneggs", value: ["2","2"] },
 { name: "Skipper42", value: ["2","3"] },
 { name: "Mom", value: ["3","1"] },
 { name: "Tom", value: ["3","2"] },
 { name: "Hated_41", value: ["3","3"] }
]

You can generate this structure like this:

您可以像这样生成此结构:

var loadarray = JSON.parse(localStorage.getItem( 'savedme' ));
var sorted = [];
for (var prop in loadarray) {
    if (loadarray.hasOwnProperty(prop)) {
        sorted.push({name:prop, value:loadarray[prop]});
    }
}
sorted.sort(function(a, b) {
    var v0 = a.value[0] - b.value[0];
    return v0 == 0 ? a.value[0] - a.value[0] : v0;
});

#2


2  

var a = [
  { "Bob": ["1", "1"] },
  { "John": ["2", "1"] },
  { "Mom": ["3", "1"] },
  { "Dad": ["1", "2"] },
  { "Tom": ["3", "2"] },
  { "Skipper42": ["2", "3"] },
  { "Hated_41": ["3", "3"] },
  { "Greeneggs": ["2", "2"] },
  { "William": ["1", "3"] }
];

a.sort(function (a, b) {
  var aa = a[Object.keys(a)],
      bb = b[Object.keys(b)];
  if (aa[0] === bb[0]) {
    return aa[1] - bb[1];
  } else {
    return aa[0] - bb[0];
  }
});
document.querySelector("#demo").innerHTML = JSON.stringify(a, null, 4);
<div id="demo"></div>

#3


0  

Keys cannot be sorted within an object.

密钥无法在对象中排序。

However, they can be processed in order using Object.keys(object).sort().

但是,可以使用Object.keys(object).sort()按顺序处理它们。

Here, I'm outputting the object to an array – sorted by the keys' values – then displaying that array:

在这里,我将对象输出到一个数组 - 按键的值排序 - 然后显示该数组:

var obj= {
 "Bob":["1","1"],
 "John":["2","1"],
 "Mom":["3","1"],
 "Dad":["1","2"],
 "Tom":["3","2"],
 "Skipper42":["2","3"],
 "Hated_41":["3","3"],
 "Greeneggs":["2","2"],
 "William":["1","3"]
}

var arr= Object.keys(obj)
          .sort(function(a, b) {
            if(obj[a][0]===obj[b][0]) {
              return obj[a][1] - obj[b][1];
            }
            else {
              return obj[a][0] - obj[b][0];
            }
          })
          .map(function(key) {
            var o= {};
            o[key]= obj[key];
            return o;
          });

document.body.innerHTML= JSON.stringify(arr);