1

I'm trying to loop over a collection of objects and get the first value (breed). Like:

  • Beagle
  • Golden Retriever
  • Corgi
  • Goldendoodle
  • Labrador Retriever

Right now I mapped over the data, but it just lists up each {}. How do I access inside of each {} ?

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" }, ...
adiga
  • 34,372
  • 9
  • 61
  • 83
kayak
  • 440
  • 3
  • 7
  • 19
  • If you know the property you want to access, try `item.breed`. Also, `map` is used to transform the values in an array to a new array. If you're just iterating and using `console.log`, try `forEach` instead – Phil Jun 03 '19 at 02:48

2 Answers2

2

Simply:

data.map(item => {
    console.log(item.breed);
})
Florentin
  • 1,433
  • 2
  • 13
  • 22
xrq0
  • 119
  • 13
2

To get the breed, extract the breed from each item.

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 syntax:

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

If you just want to log each item, use a forEach loop:

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));
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79