使用lodash的对象顺序

时间:2017-10-12 23:22:02

标签: javascript lodash

我想通过PERIOD属性对此对象进行排序。

因为有对象和数组在一起我很困惑,任何人都有任何想法?

我的代码

const obj = 
{
  "1": [
    {
      "attributes": {
        "Period": 2000,
        "name": "AP 1"
      }
    },
    {
      "attributes": {
        "Period": 1991,
        "name": "AP 2"
      }
    }
  ],
  "2": [
    {
      "attributes": {
        "Period": 1991,
        "name": "AP 3"
      }
    },
    {
      "attributes": {
        "Period": 2000,
        "name": "AP 4"
      }
    }
  ]
}

_.orderBy(obj, ['Period'], ['asc']);

console.log(obj)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js"></script>

返回结构必须是相同的输入结构。 您不需要仅丢失属性名称

我的预期代码

{
  "1": [
    {
      "attributes": {
        "Period": 1991,
        "name": "AP 2"
      }
    },
    {
      "attributes": {
        "Period": 2000,
        "name": "AP 1"
      }
    }
  ],
  "2": [
    {
      "attributes": {
        "Period": 2000,
        "name": "AP 4"
      }
    },
    {
      "attributes": {
        "Period": 1991,
        "name": "AP 3"
      }
    }
  ]
}

我使用的是lodash版本:4.17.4

1 个答案:

答案 0 :(得分:2)

我认为这就是你要找的东西:

&#13;
&#13;
[Route("api/CsxForm/Upload")]
[HttpPost]
public IHttpActionResult UploadFile(string stuff, HttpPostedFileBase file)
{
         string fileName = Path.GetFileNameWithoutExtension(file.FileName);
         string extension = Path.GetExtension(file.FileName);
            //save the file
         try
         {
            file.SaveAs("//MyDrive/Folder/" + fileName + extension);
          }
         catch (IOException exc)
         {
            return Json(new { status = "error", message = exc.Message });
         }
          return Json("Uploaded");
}
&#13;
var obj = 
{
  "1": [
    {
      "attributes": {
        "Period": 2000,
        "name": "AP 1"
      }
    },
    {
      "attributes": {
        "Period": 1991,
        "name": "AP 2"
      }
    }
  ],
  "2": [
    {
      "attributes": {
        "Period": 2000,
        "name": "AP 3"
      }
    },
    {
      "attributes": {
        "Period": 1991,
        "name": "AP 4"
      }
    }
  ]
}
 
obj = _.mapValues(obj, function(inner){
   return _.orderBy(inner, ['attributes.Period'], ['dsc']);
});

console.log(obj)
&#13;
&#13;
&#13;