简体   繁体   English

如何在性能方面适当地迭代项目并将其放入JavaScript中的新数组中?

[英]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. 我想遍历items数组,并且每个offer属性将被迭代并推送到新数组。

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. 就目前的代码而言,问题仍然存在,但是在继续进行foreach下的代码之前,我希望循环已经完成。 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. 您可以将Array#concat扩展语法...和映射数组一起使用。

 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. 您可以结合使用spread语法和reduce方法。

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. reduce()方法对一个累加器和数组中的每个元素(从左到右)应用一个函数,以将其减小为单个值。

 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 您可以使用spread syntax来组合offer密钥的值

 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) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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