检索与数组中的最高值关联的属性

时间:2014-11-21 23:39:05

标签: javascript arrays

我有一个产生以下回报的api。我试图做的是返回与最高“值”相关联的“job_id”。

"results": {
    "user": [
      {
        "calculation": "66.718*45.824",
        "job_id": "manufacturing",
        "value": 3057.3149106039559
      },
      {
        "calculation": "40.000*29.177",
        "job_id": "analysis",
        "value": 1167.0843873859146
      },
      {
        "calculation": "39.022*39.167",
        "job_id": "semiconductor",
        "value": 1528.3681864496498
      }
    ],

1 个答案:

答案 0 :(得分:0)

因此,一旦您将其反序列化为对象obj,就可以循环遍历obj.results.user

var result;
obj.results.user.forEach(function(entry) {
    if (!result || result.value < entry.value) {
        result = entry;
    }
});

更多:Array#forEach

var obj = {
  "results": {
    "user": [
      {
        "calculation": "66.718*45.824",
        "job_id": "manufacturing",
        "value": 3057.3149106039559
      },
      {
        "calculation": "40.000*29.177",
        "job_id": "analysis",
        "value": 1167.0843873859146
      },
      {
        "calculation": "39.022*39.167",
        "job_id": "semiconductor",
        "value": 1528.3681864496498
      }
    ]
  }
};
var result;
obj.results.user.forEach(function(entry) {
  if (!result || result.value < entry.value) {
    result = entry;
  }
});
snippet.log("result = " + JSON.stringify(result));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

或者如果你想得到幻想:

var result = obj.results.user.reduce(function(r, entry) {
    return !r || r.value < entry.value ? entry : r;
}, null);

更多:Array#reduce

var obj = {
  "results": {
    "user": [
      {
        "calculation": "66.718*45.824",
        "job_id": "manufacturing",
        "value": 3057.3149106039559
      },
      {
        "calculation": "40.000*29.177",
        "job_id": "analysis",
        "value": 1167.0843873859146
      },
      {
        "calculation": "39.022*39.167",
        "job_id": "semiconductor",
        "value": 1528.3681864496498
      }
    ]
  }
};
var result = obj.results.user.reduce(function(r, entry) {
  return !r || r.value < entry.value ? entry : r;
}, null);
snippet.log("result = " + JSON.stringify(result));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>