JavaScript get value from nested object [duplicate

2020-05-07 06:33发布

问题:

If this is my object:

var obj = {
bakery1: {
    small: {
        name: "Small cookie",
        price: 0.75;
    }
    large: {
        name: "Large cookie",
        price: 3.00;
    }
}
bakery2: {
    small: {
        name: "Small cookie",
        price: 1.00;
    }
    large: {
        name: "Large cookie",
        price: 4.00;
    }
}
};

How would I go about making a loop that prints every price to the console?

And when this value is printed, is there a way to trace the name?

For example if the output is 3.00 how would I make a function that gives me the name that goes with the 3.00 price?

Thanks in advance!

回答1:

To answer your question:

function printPrice(obj) {
  if (obj.price)
    console.log(obj.name, obj.price)

  else for (key in obj)
    printPrice(obj[key])
}

var obj = {
  "bakery1": {
    "small": {
      "name": "Small cookie",
      "price": 0.75
    },
    "large": {
      "name": "Large cookie",
      "price": 3
    }
  },
  "bakery2": {
    "small": {
      "name": "Small cookie",
      "price": 1
    },
    "large": {
      "name": "Large cookie",
      "price": 4
    }
  }
};

printPrice(obj)

However, for these kinds of collections, it might be better to use an array. For example, we could do something like this:

var bakeries = [
  {
    name: 'Bakery 1',
    menu: [
      {name: 'small cookie', price: 0.75},
      {name: 'large cookie', price: 3.00}
    ]
  },

  {
    name: 'Bakery 2',
    menu: [
      {name: 'small cookie', price: 1.00},
      {name: 'large cookie', price: 4.00}
    ]
  }
]

This enables us to better organize the specific properties of each item. In this case, the code to print the prices becomes much simpler:

bakeries
  .map(bakery => bakery.menu)
  .forEach(menu => menu.map(
    item => console.log(item.name, item.price)))


回答2:

run it and see how it works

var obj = {
  bakery1: {
    small: {
      name: "Small cookie",
      price: 0.75
    },
    large: {
      name: "Large cookie",
      price: 3.00
    }
  },
  bakery2: {
    small: {
      name: "Small cookie",
      price: 1.00
    },
    large: {
      name: "Large cookie",
      price: 4.00
    }
  }
};

Object.keys(obj).map((name) => {
  Object.keys(obj[name]).map((type) => document.write(`${name}-${type}-${obj[name][type].name}-${obj[name][type].price}<br/>`))
})



回答3:

Recursive function.

function objSearch(serObj){
    // For loop through the object.
    for( prop in serObj ){
        // If the property is price get the price.
        if(prop === 'price'){
            // Got the price property now return the value of price.
            console.log('I have price...', prop, '=', serObj[prop]);
            // If the property is an object send it through the function again.
        } else if(typeof serObj[prop] === 'object'){  
            // Pass the nested object.
            objSearch(serObj[prop]);
        }
    }
}

objSearch(obj);