For multiple elements in the bookings array
If there are multiple elements in the bookings array and to check if any of the element satisfies the condition Array#some can be used.
carsArray.filter(car => car.bookings.some(booking => booking.price <= 80));
To check if all the car booking prices are below 80 Array#every can be used.
carsArray.filter(car => car.bookings.every(booking => booking.price <= 80));
Live Demo:
var carsArray = [{
"name": "Record1",
"bookings": [{
"price": 50,
"actualPrice": 70,
}, {
"price": 40,
"actualPrice": 70
}]
}, {
"name": "Record2",
"bookings": [{
"price": 60,
"actualPrice": 100,
}, {
"price": 90,
"actualPrice": 160
}]
}, {
"name": "Record3",
"bookings": [{
"price": 100,
"actualPrice": 110,
}, {
"price": 120,
"actualPrice": 200
}]
}];
var atLeastOne = carsArray.filter(car => car.bookings.some(booking => booking.price <= 80));
var allCars = carsArray.filter(car => car.bookings.every(booking => booking.price <= 80));
document.getElementById('some').innerHTML = JSON.stringify(atLeastOne, 0, 4);
document.getElementById('every').innerHTML = JSON.stringify(allCars, 0, 4);
<strong>For any of the car bookings less than or equal to 80</strong>
<pre id="some"></pre>
<hr />
<strong>For all of the car bookings less than or equal to 80</strong>
<pre id="every"></pre>
For single element in bookings array
You can use JavaScript Array#filter with Arrow function as follow.
carsArray.filter(car => car.bookings[0].price <= 80);
var carsArray = [{
"name": "Record1",
"bookings": [{
"price": 50,
"actualPrice": 70,
}]
}, {
"name": "Record2",
"bookings": [{
"price": 60,
"actualPrice": 100,
}]
}, {
"name": "Record3",
"bookings": [{
"price": 100,
"actualPrice": 110,
}]
}];
var filteredArr = carsArray.filter(car => car.bookings[0].price <= 80);
console.log(filteredArr);
document.getElementById('result').innerHTML = JSON.stringify(filteredArr, 0, 4);
<pre id="result"></pre>
If there is only a single element in the bookings array, the format of the data can be changed as
var carsArray = [{
"name": "Record1",
"bookings": {
"price": 50,
"actualPrice": 70,
}
}, {
"name": "Record2",
"bookings": {
"price": 60,
"actualPrice": 100,
}
}, {
"name": "Record3",
"bookings": {
"price": 100,
"actualPrice": 110,
}
}];
var filteredArr = carsArray.filter(car => car.bookings.price <= 80);
bookingsis an array, what happens if you have more than one object there? Which one is the price?