从对象中获取值

Get values form an object

本文关键字:获取 对象      更新时间:2023-09-26

我有以下对象:(得到的内容与此代码:)

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

为什么代码不工作?我没有得到任何代码

那(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;
    }
}

原因是你的食物是一个数组。

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

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

因为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;

可以作为循环的主体,为数组

中的每个对象构建字符串。

因为food是一个数组对象,您希望像它一样处理:

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

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

更通用的方法:

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