I pushed values into an array inside of a forEach loop. When I call the array outside of the loop, I get these values:
d.data:
[{hello: 'abc', asd: '123', fgh: '345' }]
[{sdfg: '123', yo: 'ghj', fgh: '345' }]
[{gd: '123', asd: '123', bonjour: 'yui' }]
[{hello: '123', asd: '567', fgh: '345' }]
forEach Loop:
let str_arr = [];
d.data.forEach(recs => {
each_keys = Object.keys(recs);
each_vals = Object.values(recs);
each_vals.forEach(k => {
if (typeof k == 'string') {
find_key = Object.keys(recs).find(key => recs[key] === k);
str_arr.push(find_key);
}
});
});
str_arr:
["hello", "hello", "hello"]
["yo", "yo", "yo"]
["bonjour", "bonjour", "bonjour"]
[]
console.log(typeof str_arr[0] + ' = ' + str_arr[0]
Result:
string = hello
string = yo
string = bonjour
undefined = undefined
I want to push all the str_arr[0] inside one array so I do this?
let string_array = [];
if (str_arr[0] !== undefined) {
string_array.push(str_arr[0]);
}
console.log(string_array);
My result is:
hello
yo
string
(empty)
Why am I still getting the undefined value in my results?
Please login or Register to submit your answer