How can I get the contents of words from each element in the array?
[
{
words: ['help','good],
glass: 'empty'
},
{
words: ['low', 'cool'],
glass: 'full'
}
]
The expected result is:
[ 'help, 'good', 'low', 'cool' ]
With this input:
const value = [ { words: ['help','good'], glass: 'empty' }, { words: ['low', 'cool'], glass: 'full' } ] const result = value.flatMap(e => e.words); document.body.innerText = JSON.stringify(result)
Try this:
data = [{ words: ['help', 'good'], glass: 'empty' }, { words: ['low', 'cool'], glass: 'full' } ] words = [] data.forEach(function(dataSet) { words.push.apply(words, dataSet.words) }) console.log(words)
you could also use reduce if you want
const data = [ { words: ['help','good'], glass: 'empty' }, { words: ['low', 'cool'], glass: 'full' } ] console.log(data.reduce((acc,val) => [...acc, ...val.words],[]))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.