我有json对象,我想获得最低价格。以下是回复。
[
{
"room": {
"price": 217,
"available": true
}
},
{
"room": {
"price": 302,
"available": true,
}
},
{
"room": {
"price": 427,
"available": true,
}
}
]
我已尝试过Stackoverflow的解决方案,但无论如何都不会有效。
var arr = Object.keys( response ).map(function ( key ) { return response[key]; });
var min = Math.min.apply( null, arr );
请帮忙
答案 0 :(得分:3)
你可以试试这个:
let response = [
{
"room": {
"price": 217,
"available": true
}
},
{
"room": {
"price": 302,
"available": true,
}
},
{
"room": {
"price": 427,
"available": true,
}
}
];
let values = response.map(function(v) {
return v.room.price;
});
var min = Math.min.apply( null, values );
console.log(min)

使用ES2015,您也可以将它放在一行:
var min = Math.min.apply( null, response.map((v) => v.room.price));
答案 1 :(得分:1)
您有数组不是对象,因此您无法使用Object.keys()
。您也可以使用这样的扩展语法。
var data = [{
"room": {
"price": 217,
"available": true
}
}, {
"room": {
"price": 302,
"available": true,
}
}, {
"room": {
"price": 427,
"available": true,
}
}]
var min = Math.min(...data.map(e => e.room.price))
console.log(min)

答案 2 :(得分:1)
您可以使用Array.protype.reduce()
var rooms = [{
"room": {
"price": 217,
"available": true
}
},
{
"room": {
"price": 302,
"available": true,
}
},
{
"room": {
"price": 427,
"available": true,
}
}
];
console.log(rooms.reduce((prev, curr) => prev.price > curr.price ? curr : prev).room.price);
答案 3 :(得分:1)
var response = [
{
"room": {
"price": 217,
"available": true
}
},
{
"room": {
"price": 302,
"available": true,
}
},
{
"room": {
"price": 427,
"available": true,
}
}
];
debugger;
if (response && response.length > 0)
{
var min = response[0].room.price;
for (var i = 0; i < response.length; i++)
if (response[i].room.price < min)
min = response[i].room.price;
console.log(min);
}
答案 4 :(得分:0)
原生JS解决方案:
var t =[ { "room": { "price": 217, "available": true } }, { "room": { "price": 302, "available": true, } }, { "room": { "price": 427, "available": true, } } ]
var min = t.map(function(el){return el.room.price}).reduce(function(el){return Math.min(el)});
答案 5 :(得分:0)
lbrutty代码有点不对,函数总是返回第一个元素。所以有一点修复。
var t = [ { "room": { "price": 300, "available": true } }, { "room": { "price": 102, "available": true, } }, { "room": { "price": 427, "available": true, } } ];
var min = t.map(function(el){return el.room.price}).reduce(function(prevEl, el){return Math.min(prevEl, el)});