简体   繁体   中英

How to loop through a JavaScript object with a condition and then output the data?

I've made two vehicles:

var manana = {name: "manana", price: "$8,000", slots: "4"};
var walton = {name: "walton", price: "$12,000", slots: "7"};

Reacting to a button click, I would like to check a condition, to see which vehicle has eg both its price equal to $8,000 and also slots equal to 4. If it does, it would output it in a table.

You will need to hook up an event on a button. And then loop through your vehicles and test for a condition. Something like:

var manana = {name: "manana", price: "$8,000", slots: "4"};
var walton = {name: "walton", price: "$12,000", slots: "7"};

var vehicles = [manana, walton];

function eval() {
    for (var i = 0; i < vehicles.length; i++) {
        var vehicle = vehicles[i];

        if (vehicle.price == '$8,000' && vehicle.slots == '4')
            alert('found ' + vehicle.name);
    }
}

Here is the JSfiddle: https://jsfiddle.net/10qjw1gm/1/

Here's my answer, you can reuse the fonction with different prices and slots conditions or an other array :

var myArray = [{name: "manana", price: "$8,000", slots: "4"}, {name: "walton", price: "$12,000", slots: "7"}];

function retrieveNameUsingPriceAndSlots(pArray, pPrice, pSlots) {
    for(var i = 0; i < pArray.length; i++) { //Loop through the array
        var item = pArray[i];
        if(item.price === pPrice && item.slots === pSlots) {
            //If the item meets our condition, returns the name, and the code after this line wont be executed.
            return item.name;
        }
    }

    return false; 
}

console.log(retrieveNameUsingPriceAndSlots(myArray, "$8,000", "4")); //manana

Fiddle : http://jsfiddle.net/g2zuhou0/

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM