2

I am using javascript map to loop through an array of object. Today i have to loop through an array of object which looks like,

averageReport = [
    {
      "result": 150.54909908933223,
      "customer.gender": "Female"
    },
    {
      "result": 150.35230422844595,
      "customer.gender": "Male"
    }
  ];

What i tried to get only the "customer.gender",

averageReport
      .map(x => console.log(x.customer.gender)

)

I get the error "Cannot read property 'gender' of undefined" code on stackblitz

anonymous
  • 1,499
  • 2
  • 18
  • 39

3 Answers3

3

Try,

averageReport
      .map(x => console.log(x["customer.gender"])
Rohith Murali
  • 5,551
  • 2
  • 25
  • 26
3

Since you named your key customer.gender you can't use dot-notation to get the value, you have to use bracket notation ([]).

Also mapping to console.log() doesn't make much sense (since console.log() returns undefined, you are creating a new array of undefined when using map() here), just use forEach():

averageReport = [{
    "result": 150.54909908933223,
    "customer.gender": "Female"
  },
  {
    "result": 150.35230422844595,
    "customer.gender": "Male"
  }
];

averageReport.forEach(x => console.log(x["customer.gender"]));

If you want to access the property using dot-notation, you have to make customer an object and gender a property of it, like so:

averageReport = [{
    "result": 150.54909908933223,
    "customer": {
      "gender": "Female"
    }
  },
  {
    "result": 150.35230422844595,
    "customer": {
      "gender": "Male"
    }
  }
];
Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
  • why map doesnt make sense? – anonymous Aug 04 '18 at 10:23
  • @anonymous: Because `.map` returns a new array with the return values of the callback. You are supposed to use the new array. If you don't care about it, `forEach` is the more appropriate solution. – Felix Kling Aug 04 '18 at 10:24
  • I added an explanation, not only does it return a new array, it returns a new array looking like this: `[undefined, undefined]` – Luca Kiebel Aug 04 '18 at 10:25
1

Use bracket notation for accessing the customer.gender property. Try the following :

var averageReport = [ { "result": 150.54909908933223, "customer.gender": "Female" }, { "result": 150.35230422844595, "customer.gender": "Male" } ];
  
var result = averageReport.map(x =>x["customer.gender"]);
console.log(result);
amrender singh
  • 7,949
  • 3
  • 22
  • 28