按嵌套键值排序对象数组

时间:2018-03-13 16:03:40

标签: javascript arrays sorting

我有originalArray包含对象。如何按键值inventory排序数组short数组:

var originalArray = [
  {
    name: 'Store1',
    inventory: [
      { name: 'Oranges', qt: { short: 11, long: 3, med: 9 } },
      { name: 'Mango', qt: { short: 3, long: 91, med: 3 } },
      { name: 'Kiwi', qt: { short: 2, long: 91, med: 3 } },
      { name: 'Papaya', qt: { short: 8, long: 91, med: 3 } }
    ]
  },
  {
    name: 'Store2',
    inventory: [
      { name: 'Pizza', qt: { short: 31, long: 11, med: 23 } },
      { name: 'Burger', qt: { short: 1, long: 11, med: 23 } },
      { name: 'IceCream', qt: { short: 111, long: 11, med: 323 } }
    ]
  }
];

所需的输出是:

var sorted = [
  {
    name: 'Store1',
    inventory: [
      { name: 'Kiwi', qt: { short: 2, long: 91, med: 3 } },
      { name: 'Mango', qt: { short: 3, long: 91, med: 3 } },
      { name: 'Papaya', qt: { short: 8, long: 91, med: 3 } },
      { name: 'Oranges', qt: { short: 11, long: 3, med: 9 } }
    ]
  },
  {
    name: 'Sotre2',
    inventory: [
      { name: 'Burger', qt: { short: 1, long: 11, med: 23 } },
      { name: 'Pizza', qt: { short: 31, long: 11, med: 23 } },
      { name: 'IceCream', qt: { short: 111, long: 11, med: 323 } }
    ]
  }
];

除了inventory数组排序short之外,我不需要任何其他内容。

inventory数组的所有项都按dsc顺序排序。性能不是问题,也不是语言规范限制,只是限制是我不能使用外部库。

是否有一种理智的方式来执行此操作,或者我需要将inventory插入到中间变量中对其进行排序并创建新的对象数组,其中inventory已排序。

1 个答案:

答案 0 :(得分:2)

var originalArray = [
  {
    name: 'Store1',
    inventory: [
      { name: 'Oranges', qt: { short: 11, long: 3, med: 9 } },
      { name: 'Mango', qt: { short: 3, long: 91, med: 3 } },
      { name: 'Kiwi', qt: { short: 2, long: 91, med: 3 } },
      { name: 'Papaya', qt: { short: 8, long: 91, med: 3 } }
    ]
  },
  {
    name: 'Store2',
    inventory: [
      { name: 'Pizza', qt: { short: 31, long: 11, med: 23 } },
      { name: 'Burger', qt: { short: 1, long: 11, med: 23 } },
      { name: 'IceCream', qt: { short: 111, long: 11, med: 323 } }
    ]
  }
];

for (var i = 0; i < originalArray.length; i++) {
  originalArray[i].inventory.sort(function(a, b) { return a.qt.short - b.qt.short; });
}

console.log(originalArray);