如何从数组对象返回多个值作为新变量?

时间:2018-08-02 13:50:15

标签: javascript arrays object

我的数组如下:

create table #tablename (id int ,someval int)

insert into  #tablename values (1,500)

insert into  #tablename values (3,492.23)

 SELECT ISNULL((SELECT isnull( ID, 1 ) FROM #tablename WHERE ID = 1),2) ,
 ISNULL((SELECT isnull( someval, 0 ) FROM #tablename WHERE ID = 1),0)
 union all
 SELECT ISNULL((SELECT isnull( ID, 2 ) FROM #tablename WHERE ID = 2),2) ,
 ISNULL((SELECT isnull( someval, 0 ) FROM #tablename WHERE ID = 2),0)
 union all
 SELECT ISNULL((SELECT isnull( ID, 3 ) FROM #tablename WHERE ID = 3),2) ,
 ISNULL((SELECT isnull( someval, 0 ) FROM #tablename WHERE ID = 3),0)

我正在尝试查看哪个类别的var points = [{category: "Category A", correct: "0"},{category: "Category B", correct: "4"}]; 数量最多。我首先在数组映射上使用correct来确定哪一个是最高值(它返回Math.max。)但是当我尝试扩展该返回值时,它开始默认为NaN。

4

var res = Math.max.apply(Math,points.map(function(k){ return k.correct; })); 在这种情况下将返回o.correct

JSFiddle


我尝试过的事情:

  1. 将我的退货切换到4

    ->这将返回“ NaN”

  2. 将其作为函数进行处理并将两个变量都存储在k.category中,这将提取对象的两个值,但对数组中的两个对象都执行此操作。

    Math.max

关于将这些内容存储为2个单独的变量的任何想法,我以后可以参考?

3 个答案:

答案 0 :(得分:1)

您可以对数组进行排序并获取第一个元素

var points = [{category: "Category A", correct: "0"},{category: "Category B", correct: "4"}];
var sorted = points.sort((a,b)=>b.correct - a.correct)
var highest = sorted[0];
alert(highest.category + highest.correct);

与对象分解相同的事物

var points = [{category: "Category A", correct: "0"},{category: "Category B", correct: "4"}];   
var {category:highestCateogry,correct:highestCorrect} = points.sort((a,b)=>b.correct - a.correct)[0];
alert(highestCateogry + highestCorrect); 

答案 1 :(得分:1)

您可以使用Array reduce

let points = [{category: "Category A", correct: "0"},{category: "Category B", correct: "4"},{category: "Category C", correct: "1"},{category: "Category D", correct: "5"},{category: "Category E", correct: "0"}];


const max = points.reduce((currentMax,newMax) => { 
return +currentMax.correct  < +newMax.correct ?  newMax :currentMax
})

console.log(max)

答案 2 :(得分:0)

您有NaN,因为正确的是string而不是number。使用parseInt函数将字符串转换为整数