在react native

时间:2018-09-13 14:04:09

标签: javascript arrays json react-native

我有一些看起来像这样的json数据:

const data = {
  "stores": [
    {
      "name": "s1",
      "id": "6fbyYnnqUwAEqMmci0cowU",
      "customers": [
        {
          "id": "4IhkvkCG9WWOykOG0SESWy",
          "name": "customer2",
        },
        {
          "id": "4IhkfikCG9WWOykOG0SESWy",
          "name": "customer1",
        },
        {
          "id": "9IfkvkCG9WWOykOG0SESWy",
          "name": "customer100",
        },
      ]
    },
    {
      "name": "s2",
      "id": "2D1fTgjAJ20ImiAqsWAEEI",
      "customers": [
        {
          "id": "3dfkvkCG9WWOykOG0SESWy",
          "name": "customer9",
        },
      ]
    },
    {
      "name": "s3",
      "id": "6rxmPFzIHKQ0EOAGGkAwKg",
      "customers": [
        {
          "id": "7IfkvkCG9WWOykOG0SESWy",
          "name": "customer7",
        },
      ]
    }
  ]
}

我需要按照客户名称对数据进行排序。 到目前为止,我所做的事情:

const sortedData = data.stores.sort(function(c1, c2) {
   return c1.customers[0].name < c1.customers[0].name;
}).map(storeInfo => (
  // Need to do something else with sorted data
)

我的方法似乎不起作用,因为我认为它不会进入嵌套级别。任何帮助表示赞赏。

预期结果: 首先对每个商店内的顾客列表(按字母顺序)排序,然后对商店中的顾客列表进行排序。

1 个答案:

答案 0 :(得分:1)

我试图分两个阶段修复它。我不确定这是最佳方法,但可以为您提供帮助。

const sortedData = [];

// Sort the customers for each store
for (var i = 0, len = data.stores.length; i < len; i++) {
    sortedData[i] = data.stores[i];
    sortedData[i]['customers'] = data.stores[i].customers.sort(function(c1, c2) {
        return c1.name > c2.name;
    });
}

// Sort the stores by first customer name
sortedData.sort(function(c1, c2) {
    return c1.customers[0].name > c2.customers[0].name;
});

console.log(sortedData);