Изменить порядок массива объектов

  • Автор темы Сергей Карабанов
  • 31
  • Обновлено
  • 16, May 2024
  • #1
 

var originalObject = [{

"CatID": 15,

"Currently": "is One",

"ParentID": 16,

"Should": "should be One"

}, {

"CatID": 17,

"Currently": "is Two",

"ParentID": 16,

"Should": "should be Two"

}, {

"CatID": 18,

"Currently": "is Three",

"ParentID": 16,

"Should": "should be Three"

}, {

"CatID": 22,

"Currently": "is Four",

"ParentID": 16,

"Should": "should be Seven"

}, {

"CatID": 28,

"Currently": "is Five",

"ParentID": 16,

"Should": "should be Eight"

}, {

"CatID": 92,

"Currently": "is Six",

"ParentID": 18,

"Should": "should be Four"

}, {

"CatID": 30,

"Currently": "is Seven",

"ParentID": 92,

"Should": "should be Five"

}, {

"CatID": 95,

"Currently": "is Nine",

"ParentID": 30,

"Should": "should be Six"

}];

var localParentID = '';

var localArr = [];

for (var i in originalObject) {

var iObj = originalObject[i];

$('#displayDiv').append('Parent is ' + iObj['ParentID'] + ' ' + iObj['Currently'] + ' ' + iObj['CatID'] + ' ' + iObj['Should'] + '<br />');

}

Code (markup): How can I sort the array above so that the ouput matches "should" order as opposed to "currently" order? It should be ordered by currently with should ParentID being attached to currently CatID. Can't quite make this behave.

Сергей Карабанов


Рег
11 Apr, 2013

Тем
1

Постов
3

Баллов
13
  • 21, May 2024
  • #2
Ну, во-первых, замените текст «должно быть x» только на это число. Затем выполните Array.sort с обратным вызовом, чтобы обратный вызов мог получить доступ к свойству объекта «Should». (это не значит, что свойство должно начинаться с заглавной буквы, подразумевающей, что это на самом деле КЛАСС)
 var data = [

{

"CatID": 15,

"Currently": "is One",

"ParentID": 16,

"Should": 1

}, {

"CatID": 17,

"Currently": "is Two",

"ParentID": 16,

"Should": 4

}, {

"CatID": 18,

"Currently": "is Three",

"ParentID": 16,

"Should": 3

}, {

"CatID": 22,

"Currently": "is Four",

"ParentID": 16,

"Should": 7

}, {

"CatID": 28,

"Currently": "is Five",

"ParentID": 16,

"Should": 8

}, {

"CatID": 92,

"Currently": "is Six",

"ParentID": 18,

"Should": 2

}, {

"CatID": 30,

"Currently": "is Seven",

"ParentID": 92,

"Should": 5

}, {

"CatID": 95,

"Currently": "is Nine",

"ParentID": 30,

"Should": 6

}

];

function shouldCompare(a, b) { return a.Should - b.Should; }

data.sort(shouldCompare);

Код (разметка): Вот и все. Массив находится в порядке «следует».
 

vodka07


Рег
22 Jul, 2014

Тем
0

Постов
1

Баллов
1
Тем
49554
Комментарии
57426
Опыт
552966

Интересно