playing around with foreach fuction atm, and trying to get .data out of it.
const foreachfunc = (data = null) => { data.forEach((element, index) => { console.log('element = ' + element, 'index = ' + index) let head = element.head console.log(head) }); }; const myarray = ["test1", "test2"] foreachfunc(myarray)
okay so right now it outputs:
element = test1 index = 0 undefined element = test2 index = 1 undefined
and it does makes sense since i haven’t giving ‘head’ any data yet. But is it possible to give ‘head’ data within ‘myarray’?
Advertisement
Answer
Problem is with your array as it does not contain data that you are trying to access. check updated code below
const foreachfunc = (data = null) => { data.forEach((element, index) => { console.log('element = ' + element.text, 'index = ' + index) let head = element.head console.log(head) }); }; const myarray = [{head:"head1",text:"text1"},{head:"head2",text:"text2"}] foreachfunc(myarray)