简体   繁体   中英

How can I properly iterate through items and put it in a new array in JavaScript in terms of performance?

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? Any help would be much appreciated.

Update: Okay, so first, 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.

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); 

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); 

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) 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM