如何获取对象的值?

时间:2019-06-03 02:47:41

标签: javascript arrays object

我正在尝试遍历一组对象并获取第一个值(品种)。喜欢:

  • 小猎犬
  • 金毛寻回犬
  • 柯基犬
  • Goldendoodle
  • 拉布拉多犬

现在我映射了数据,但是它只是列出了每个{}。如何访问每个{}的内部?

const data = [
    { 
        "breed": "Beagle",
        "characteristics": "playful" 
    },
    {
        "breed": "Golden Retriever", 
        "characteristics": "calm" 
    },
    {
        "breed": "Corgi", 
        "characteristics": "bright" 
    },
    {
        "breed": "Goldendoodle", 
        "characteristics": "gentle" 
    },
    {
        "breed": "Labrador Retriever", 
        "characteristics": "loyal" 
    },
]


data.map(item => {
    console.log(item);
})
// Object { breed: "Beagle", characteristics: "playful" }, Object { breed: "Golden Retriever", characteristics: "calm" }, ...

2 个答案:

答案 0 :(得分:2)

data.map(item => { console.log(item.breed); })

答案 1 :(得分:2)

要获得品种,请从每个项目中提取breed

const data = [{"breed":"Beagle","characteristics":"playful"},{"breed":"Golden Retriever","characteristics":"calm"},{"breed":"Corgi","characteristics":"bright"},{"breed":"Goldendoodle","characteristics":"gentle"},{"breed":"Labrador Retriever","characteristics":"loyal"}];

const res = data.map(({ breed }) => breed);
console.log(res);

ES5语法:

var data = [{"breed":"Beagle","characteristics":"playful"},{"breed":"Golden Retriever","characteristics":"calm"},{"breed":"Corgi","characteristics":"bright"},{"breed":"Goldendoodle","characteristics":"gentle"},{"breed":"Labrador Retriever","characteristics":"loyal"}];

var res = data.map(function(item) {
  return item.breed
});
console.log(res);

如果您只想记录每个项目,请使用forEach循环:

const data = [{"breed":"Beagle","characteristics":"playful"},{"breed":"Golden Retriever","characteristics":"calm"},{"breed":"Corgi","characteristics":"bright"},{"breed":"Goldendoodle","characteristics":"gentle"},{"breed":"Labrador Retriever","characteristics":"loyal"}];

data.forEach(({ breed }) => console.log(breed));