从对象中获取值

时间:2015-08-21 08:56:18

标签: javascript arrays object

我有以下对象: (使用此代码获取内容:)

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"}]}

我是JavaScript的新手,想要获得一些值,例如“Homestyle Breakfast”(最后一个)的所有值

thisResult = '';

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

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

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

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

        alert(thisResult);

为什么那段代码不起作用? 我没有得到任何代码。

6 个答案:

答案 0 :(得分:1)

那个(food)是一个数组,所以你应该迭代它,或者你应该知道你需要显示哪个键。例如,您是否想要最后一个应更改objData.food objData.food[4]objData.food[objData.food.length - 1]

你可以用:

循环它
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 :(得分:1)

原因是你的食物是一个阵列。

要解决此问题,您可以创建一个函数来查找具有特定名称的食物对象,然后返回该对象。

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);

答案 2 :(得分:0)

因为food是一个数组,所以你应该首先按索引访问数组,以便访问其中的对象:

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;

这可以是循环的主体,为数组中的每个对象构建字符串

答案 3 :(得分:0)

因为food是一个数组对象而你想要这样对待:

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 4 :(得分:0)

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');

答案 5 :(得分:0)

更通用的方法:

&#13;
&#13;
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>');
&#13;
&#13;
&#13;