Reputation: 13434
So this is my code:
let newArr = []
const items = [
{
name: 'JTB 0110-01',
offers: ['one', 'two']
},
{
name: 'LOBA CHEMIE',
offers: ['three', 'four', 'five']
},
//more
]
items.forEach(item => {
item.offers.forEach(i => newArr.push(i));
})
//more code
I want to loop over the items array and each offers property will be iterated and pushed to the new array.
For now the code is working, the problem though is before proceeding to the code under the foreach
, I want the looping to be done already. How can I properly do this?
Sorry for not being clear. I want it to be synchronous like before going to the code after iteration, I want the looping to be done.
Upvotes: -2
Views: 72
Reputation: 50291
You can use spread syntax
to combine the value of offer
key
let newArr = []
const items = [{
name: 'JTB 0110-01',
offers: ['one', 'two']
},
{
name: 'LOBA CHEMIE',
offers: ['three', 'four', 'five']
}
]
var newArray = [];
items.forEach(function(item) {
// // ... is spread syntax which will combine the array
newArray.push(...item.offers)
})
console.log(newArray)
Upvotes: -1
Reputation: 386550
You could use Array#concat
with spread syntax ...
and mapped array.
var items = [{ name: 'JTB 0110-01', offers: ['one', 'two'] }, { name: 'LOBA CHEMIE', offers: ['three', 'four', 'five'] }],
array = Array.prototype.concat(...items.map(({offers}) => offers));
console.log(array);
Upvotes: 2
Reputation: 48337
You can use spread
syntax in combination with reduce
method.
The reduce()
method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
const items = [ { name: 'JTB 0110-01', offers: ['one', 'two'] }, { name: 'LOBA CHEMIE', offers: ['three', 'four', 'five'] }]
let result = items.reduce(function(acc,elem){
acc.push(...elem.offers);
return acc;
},[]);
console.log(result);
Upvotes: 0