无法访问看起来像JSON的数组内的数据。 JavaScript的

时间:2017-03-29 22:54:43

标签: javascript arrays sorting append

下面,我有一个看起来像JSON数据的数组。我通过查询并将其推送到var test = [];来获得此结果。我将字符串和数字附加到test数组中的方法是运行test.push({item_name: name, number_of_items: number});。需要明确的是,它不是JSON:

[{"item_name":"Peri Peri Chicken","number_of_items":6},{"item_name":"Deep fried beef","number_of_items":22},{"item_name":"Roast chicken","number_of_items":7},{"item_name":"Chow Mein","number_of_items":3},{"item_name":"Sweet and sour noodles","number_of_items":5},{"item_name":"Steak","number_of_items":32}]

现在,我想对数组进行排序,以便显示从最大number_of_items到最小number_of_items的数组。

我试图像对待JSON数组一样对它进行排序,但它没有工作,因为我已经意识到我无法使用test.number_of_items访问该数组中的元素。我尝试使用THIS方法对数组进行排序,但它并不适合我,因为我的数据不是JSON。

如果有人能告诉我是否有更好的方法将多个数据附加到阵列的同一索引中,并且将来能够更轻松地访问这些元素,那么这也会非常有用吗?例如,在索引1上,我会有类似(elem1: string1, elem2: number1)的内容,然后索引2 (elem1: string2, elem2: number2)和...

2 个答案:

答案 0 :(得分:2)

试试这个:

  test = [{"item_name":"Peri Peri Chicken","number_of_items":6},   {"item_name":"Deep fried beef","number_of_items":22},{"item_name":"Roast chicken","number_of_items":7},{"item_name":"Chow Mein","number_of_items":3},    {"item_name":"Sweet and sour noodles","number_of_items":5},{"item_name":"Steak","number_of_items":32}];

  test.sort(function(a, b) {
    return a.number_of_items - b.number_of_items;
  });

execution image 祝你好运

答案 1 :(得分:0)

您可以将其解析为JSON,对其进行排序,然后将其重新转换为字符串,如下所示:

var array = [
    { "item_name": "Peri Peri Chicken", "number_of_items": 6 },
    { "item_name": "Deep fried beef", "number_of_items": 22 },
    { "item_name": "Roast chicken", "number_of_items": 7 },
    { "item_name": "Chow Mein", "number_of_items": 3 },
    { "item_name": "Sweet and sour noodles", "number_of_items": 5 },
    { "item_name": "Steak", "number_of_items": 32 }
];

var compare = (a,b) => {
  if (a.number_of_items < b.number_of_items)
    return 1;
  if (a.number_of_items > b.number_of_items)
    return -1;
  return 0;
};

var test = JSON.parse(array);
test.sort(compare);
array = JSON.stringify(test);