Json数据中字段的最大数量

时间:2017-05-03 18:54:12

标签: javascript ecmascript-6 lodash

我的Json数据如下

[{
  "Name": "PieChart",
  "Id": "1",
  "ColumnLocation": "0",
  "RowLocation": "0"
}, {
  "Name": "Calendar",
  "Id": "2",
  "ColumnLocation": "1",
  "RowLocation": "0"
}, {
  "Name": "FavouriteFilter",
  "Id": "3",
  "ColumnLocation": "2",
  "RowLocation": "0"
}, {
  "Name": "FilterResults",
  "Id": "4",
  "ColumnLocation": "0",
  "RowLocation": "1"
}, {
  "Name": "Watched",
  "Id": "5",
  "ColumnLocation": "1",
  "RowLocation": "1"
}]

我需要找到上述数据的最高NumberLocation数。我需要这些信息,因为我可以根据这些列数绘制我的仪表板。

3 个答案:

答案 0 :(得分:4)

减少

const a = [{
  "Name": "PieChart",
  "Id": "1",
  "ColumnLocation": "0",
  "RowLocation": "0"
}, {
  "Name": "Calendar",
  "Id": "2",
  "ColumnLocation": "1",
  "RowLocation": "0"
}, {
  "Name": "FavouriteFilter",
  "Id": "3",
  "ColumnLocation": "2",
  "RowLocation": "0"
}, {
  "Name": "FilterResults",
  "Id": "4",
  "ColumnLocation": "0",
  "RowLocation": "1"
}, {
  "Name": "Watched",
  "Id": "5",
  "ColumnLocation": "1",
  "RowLocation": "1"
}];

const r = a.reduce((a, c) => (c.ColumnLocation > a) ? c.ColumnLocation : a, 0);

console.log(r)

答案 1 :(得分:2)

您可以映射每个ColumnLocation键并使用Math.max函数来获得最高价值。

var data = [{"Name":"PieChart","Id":"1","ColumnLocation":"0","RowLocation":"0"},{"Name":"Calendar","Id":"2","ColumnLocation":"1","RowLocation":"0"},{"Name":"FavouriteFilter","Id":"3","ColumnLocation":"2","RowLocation":"0"},{"Name":"FilterResults","Id":"4","ColumnLocation":"0","RowLocation":"1"},{"Name":"Watched","Id":"5","ColumnLocation":"1","RowLocation":"1"}], 
    res = data.map(v => v.ColumnLocation);
    
    //console.log(Math.max.apply(Math, res));
    console.log(Math.max(...res));

答案 2 :(得分:0)

使用lodash maxBy函数删除解决方案:

const maxColumnLocation = _.maxBy(data, 'ColumnLocation').ColumnLocation;