I have an array with different values (in JSON structure), I need to get one item on the array based on another value.
This is what I did so far:
var orders= [{
"id": 1,
"order": "11"
},
{
"id": 2,
"order": "22"
},
{
"id": 3,
"order": "33"
}];
var order = $.grep(orders, function (e) { return e.order === '22'; })[0];
var orderID = order ? order.id : 0;
Is this the simplest way to do it?
With ES6, you could use Array#find
var orders= [{ id: 1, order: "11" }, { id: 2, order: "22" }, { id: 3, order: "33" }], order = orders.find(o => o.order === "22"), orderID = order ? order.id : 0; console.log(orderID);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.