Ich habe folgendes Objekt: (habe den Inhalt mit diesem Code bekommen :)

alert(JSON.stringify(objData));

{"food":[{"name":"Belgian Waffles","price":"$5.95","description":"Two of our famous Belgian Waffles with plenty of real maple syrup","calories":"650"},{"name":"Strawberry Belgian Waffles","price":"$7.95","description":"Light Belgian waffles covered with strawberries and whipped cream","calories":"900"},{"name":"Berry-Berry Belgian Waffles","price":"$8.95","description":"Light Belgian waffles covered with an assortment of fresh berries and whipped cream","calories":"900"},{"name":"French Toast","price":"$4.50","description":"Thick slices made from our homemade sourdough bread","calories":"600"},{"name":"Homestyle Breakfast","price":"$6.95","description":"Two eggs, bacon or sausage, toast, and our ever-popular hash browns","calories":"950"}]}

Ich bin wirklich neu in JavaScript und möchte einige Werte erhalten, zum Beispiel alle Werte von "Homestyle Breakfast" (letzter)

thisResult = '';

        thisResult += 'Name: ' + objData.food.name;

        thisResult += '\nPrice: ' + objData.food.price;

        thisResult += '\nDescription: ' + objData.food.description;

        thisResult += '\nCalories: ' + objData.food.calories;

        alert(thisResult);

Warum funktioniert dieser Code nicht? Ich bekomme nichts mit diesem Code.

1
ESA 21 Aug. 2015 im 11:56

6 Antworten

Beste Antwort

Das (food) ist ein Array, daher sollten Sie es iterieren oder wissen, welchen Schlüssel Sie anzeigen müssen. Zum Beispiel möchten Sie den letzten, den Sie mit objData.food[4] oder objData.food[objData.food.length - 1] ändern sollten.

Sie können es schleifen mit:

for (var i = 0; i < objData.food.length; i++) {
    var food = objData.food[i];

    // for example display only that with name = Homestyle Breakfast
    if (food.name === 'Homestyle Breakfast') {
        thisResult = '';
        thisResult += 'Name: ' + food.name;
        thisResult += '\nPrice: ' + food.price;
        thisResult += '\nDescription: ' + food.description;
        thisResult += '\nCalories: ' + food.calories;
    }
}
1
huysentruitw 21 Aug. 2015 im 09:07
var foodStore = {"food":[{"name":"Belgian Waffles","price":"$5.95","description":"Two of our famous Belgian Waffles with plenty of real maple syrup","calories":"650"},{"name":"Strawberry Belgian Waffles","price":"$7.95","description":"Light Belgian waffles covered with strawberries and whipped cream","calories":"900"},{"name":"Berry-Berry Belgian Waffles","price":"$8.95","description":"Light Belgian waffles covered with an assortment of fresh berries and whipped cream","calories":"900"},{"name":"French Toast","price":"$4.50","description":"Thick slices made from our homemade sourdough bread","calories":"600"},{"name":"Homestyle Breakfast","price":"$6.95","description":"Two eggs, bacon or sausage, toast, and our ever-popular hash browns","calories":"950"}]}, // your object
    find = function find( type, field, value ) {
        return foodStore[type].filter(function (record) {
            if (record[field] === value) return true;
            return false;
        })[0];
    },
    mySearch = find('food', 'name', 'Homestyle Breakfast');
0
Shilly 21 Aug. 2015 im 09:10

Ein allgemeinerer Ansatz:

var obj = { "food": [{ "name": "Belgian Waffles", "price": "$5.95", "description": "Two of our famous Belgian Waffles with plenty of real maple syrup", "calories": "650" }, { "name": "Strawberry Belgian Waffles", "price": "$7.95", "description": "Light Belgian waffles covered with strawberries and whipped cream", "calories": "900" }, { "name": "Berry-Berry Belgian Waffles", "price": "$8.95", "description": "Light Belgian waffles covered with an assortment of fresh berries and whipped cream", "calories": "900" }, { "name": "French Toast", "price": "$4.50", "description": "Thick slices made from our homemade sourdough bread", "calories": "600" }, { "name": "Homestyle Breakfast", "price": "$6.95", "description": "Two eggs, bacon or sausage, toast, and our ever-popular hash browns", "calories": "950" }] };

function getFood(name) {
    var item;
    obj.food.some(function (a) {
        if (a.name === name) {
            item = a;
            return true;
        }
    });
    return item
}

function printFoodItem(item) {
    var cols = [{ name: 'Name' }, { price: 'Price' }, { description: 'Description' }, { calories: 'Calories' }];
    return cols.reduce(function (r, a, i) {
        var k = Object.keys(a);
        k in item && r.push(a[k] + ': ' + item[k]);
        return r;
    }, []).join('\n');
}

document.write('<pre>' + printFoodItem(getFood('French Toast')) + '</pre>');
0
Nina Scholz 21 Aug. 2015 im 09:30

Weil food ein Array-Objekt ist und Sie es so behandeln möchten:

var objData = {
  "food": [{
    "name": "Belgian Waffles",
    "price": "$5.95",
    "description": "Two of our famous Belgian Waffles with plenty of real maple syrup",
    "calories": "650"
  }, {
    "name": "Strawberry Belgian Waffles",
    "price": "$7.95",
    "description": "Light Belgian waffles covered with strawberries and whipped cream",
    "calories": "900"
  }, {
    "name": "Berry-Berry Belgian Waffles",
    "price": "$8.95",
    "description": "Light Belgian waffles covered with an assortment of fresh berries and whipped cream",
    "calories": "900"
  }, {
    "name": "French Toast",
    "price": "$4.50",
    "description": "Thick slices made from our homemade sourdough bread",
    "calories": "600"
  }, {
    "name": "Homestyle Breakfast",
    "price": "$6.95",
    "description": "Two eggs, bacon or sausage, toast, and our ever-popular hash browns",
    "calories": "950"
  }]
}


thisResult = '';

thisResult += 'Name: ' + objData.food[0].name;

thisResult += '\nPrice: ' + objData.food[0].price;

thisResult += '\nDescription: ' + objData.food[0].description;

thisResult += '\nCalories: ' + objData.food[0].calories;

alert(thisResult);
0
Alex Char 21 Aug. 2015 im 09:03

Da food ein Array ist, sollten Sie zuerst über den Index auf das Array zugreifen, um Zugriff auf das darin enthaltene Objekt zu erhalten:

thisResult = '';

thisResult += 'Name: ' + objData.food[0].name;

thisResult += '\nPrice: ' + objData.food[0].price;

thisResult += '\nDescription: ' + objData.food[0].description;

thisResult += '\nCalories: ' + objData.food[0].calories;

Dies kann der Hauptteil einer Schleife sein, in der Sie die Zeichenfolge für jedes Objekt im Array erstellen

0
Raulucco 21 Aug. 2015 im 08:59

Der Grund ist, dass Ihr Essen eine Reihe ist.

Um dies zu beheben, können Sie eine Funktion erstellen, die ein Lebensmittelobjekt mit einem bestimmten Namen findet und dieses Objekt dann zurückgibt.

var objData = {"food":[{"name":"Belgian Waffles","price":"$5.95","description":"Two of our famous Belgian Waffles with plenty of real maple syrup","calories":"650"},{"name":"Strawberry Belgian Waffles","price":"$7.95","description":"Light Belgian waffles covered with strawberries and whipped cream","calories":"900"},{"name":"Berry-Berry Belgian Waffles","price":"$8.95","description":"Light Belgian waffles covered with an assortment of fresh berries and whipped cream","calories":"900"},{"name":"French Toast","price":"$4.50","description":"Thick slices made from our homemade sourdough bread","calories":"600"},{"name":"Homestyle Breakfast","price":"$6.95","description":"Two eggs, bacon or sausage, toast, and our ever-popular hash browns","calories":"950"}]};
var json = JSON.stringify(objData);

function getObjectByName(name){
    var food = {};
    for(var i=0; i< objData.food.length;i++){
        if(objData.food[i].name === name){
            food =  objData.food[i];
        }
    }
    return food;
}

var belgWaffle = getObjectByName('Belgian Waffles');
alert(belgWaffle.name+"\n"+belgWaffle.description);
1
Pindo 21 Aug. 2015 im 09:12