Riccardo Pezzolati
Riccardo Pezzolati

Reputation: 359

Foreach in an array object in javascript I can't access the elements

This is my object array

[{ docNum: "7"
  docType: {code: "J", description: "Kons", lang: "I", category: "DELIVERY"}
  docYear: "0000"
  posNum: "000010"
},
{ docNum: "11"
  docType: {code: "J", description: "Kons", lang: "I", category: "DELIVERY"}
  docYear: "2145"
  posNum: "000020"
},
]

I need to access the DocNum property, I try this

array.forEach(element =>{
console.log("DocNum",element.docNum);
});

But in console I have this: "DocNum undefined"

Upvotes: 0

Views: 495

Answers (2)

Nonik
Nonik

Reputation: 655

your object is wrong, you need to add commas at properties

var array=[{ docNum: "7",
  docType: {code: "J", description: "Kons", lang: "I", category: "DELIVERY"},
  docYear: "0000",
  posNum: "000010"
},
{ docNum: "11",
  docType: {code: "J", description: "Kons", lang: "I", category: "DELIVERY"},
  docYear: "2145",
  posNum: "000020"
},
];

array.forEach(element =>{
console.log("DocNum",element.docNum);
});

Upvotes: 2

NoNickAvailable
NoNickAvailable

Reputation: 398

let arr = [{
    docNum: "7",
    docType: {
      code: "J",
      description: "Kons",
      lang: "I",
      category: "DELIVERY"
    },
    docYear: "0000",
    posNum: "000010"
  },
  {
    docNum: "11",
    docType: {
      code: "J",
      description: "Kons",
      lang: "I",
      category: "DELIVERY"
    },
    docYear: "2145",
    posNum: "000020"
  }
]

arr.forEach(element => {
  console.log("DocNum", element.docNum);
});

You missed the commas after the properties

Upvotes: 2

Related Questions