如何使用通配符从JSON对象中的任何属性获取最大值和最小值

时间:2017-08-17 16:04:10

标签: javascript json

我需要从类似于此的JSON对象中获取以 Count 结尾的所有属性的最大值和最小值。我希望得到18分为最高分,3分为分数。

我可以获得单个属性(Getting max value(s) in JSON array)的最大值,但不能获得以计数结尾的任何内容。

[
{Period: 01/2017, Alpha: 5, AlphaCount: 10, Bravo: 3, BravoCount: 7, Charlie: 9, CharlieCount: 3}
{Period: 02/2017, Alpha: 2, AlphaCount: 4, Bravo: 3, BravoCount: 6, Charlie: 9, CharlieCount: 13}
{Period: 03/2017, Alpha: 6, AlphaCount: 8, Bravo: 3, BravoCount: 12, Charlie: 9, CharlieCount: 18}
]

3 个答案:

答案 0 :(得分:1)

你可以遍历整个数组并获取每个对象的密钥,使用indexOf()检查密钥中是否有'Count',然后检查它是否为max。像这样的东西:

var arr = [
{Period: 01/2017, Alpha: 5, AlphaCount: 10, Bravo: 3, BravoCount: 7, Charlie: 9, CharlieCount: 3},
{Period: 02/2017, Alpha: 2, AlphaCount: 4, Bravo: 3, BravoCount: 6, Charlie: 9, CharlieCount: 13},
{Period: 03/2017, Alpha: 6, AlphaCount: 8, Bravo: 3, BravoCount: 12, Charlie: 9, CharlieCount: 18}
];
var max = -1;
arr.forEach(function(ob){
   var keys = Object.keys(ob);
   keys.forEach(x => max = x.indexOf('Count')>=0 && ob[x] >max ? ob[x]:max);
})
console.log(max);

答案 1 :(得分:1)

const sample = [
  {Period: '01/2017', Alpha: 5, AlphaCount: 10, Bravo: 3, BravoCount: 7, Charlie: 9, CharlieCount: 3},
  {Period: '02/2017', Alpha: 2, AlphaCount: 4, Bravo: 3, BravoCount: 6, Charlie: 9, CharlieCount: 13},
  {Period: '03/2017', Alpha: 6, AlphaCount: 8, Bravo: 3, BravoCount: 12, Charlie: 9, CharlieCount: 18}
]

const arr = []
function extractCount (item) {
  return Object.keys(item).forEach(i =>  {
    /Count$/.test(i) && arr.push(item[i]);
  })
}

sample.map(extractCount)

console.log(Math.max(...arr));
console.log(Math.min(...arr));

希望这有帮助!

答案 2 :(得分:1)

写一个扩展版只是为了看看每个部分是如何工作的,从这里你可以根据自己的喜好进行修改,希望这会有所帮助:

var arr = [
{Period: 01/2017, Alpha: 5, AlphaCount: 10, Bravo: 3, BravoCount: 7, Charlie: 9, CharlieCount: 3},
{Period: 02/2017, Alpha: 2, AlphaCount: 4, Bravo: 3, BravoCount: 6, Charlie: 9, CharlieCount: 13},
{Period: 03/2017, Alpha: 6, AlphaCount: 8, Bravo: 3, BravoCount: 12, Charlie: 9, CharlieCount: 18}
];

function getMaxThatEndsWith(arr, ending) {
	var maxVal;
	for(var i = 0; i < arr.length; i++) {
		var obj = arr[i];
		var matches = getFieldsThatEndWith(obj, ending);
		for (var j = 0; j < matches.length; j++) {
			if (!maxVal || parseInt(obj[matches[j]]) > maxVal) {
				maxVal = obj[matches[j]];
			}
		}
	}
	return maxVal;
}

function getFieldsThatEndWith(obj, like) {
	var matches = [];
	var propertyNames = Object.getOwnPropertyNames(obj);
	for(var i = 0; i < propertyNames.length; i++) {
		var propName = propertyNames[i];
		if (propName.endsWith(like)) {
			matches.push(propName);
		}
	}
	return matches;
}

var maxValue = getMaxThatEndsWith(arr, 'Count');

console.log(maxValue);