简体   繁体   English

Javascript:对象数组到包含值数组的对象-最有效的方式?

[英]Javascript: Array of objects to object containing arrays of values - most performant way?

Desired: loop over a single array of objects, and construct multiple arrays for assigning to an object, based on the keys in those objects in most concise and performant manner. 所需:循环访问单个对象数组,并以最简洁和高效的方式根据对象中的键构造多个数组以分配给对象。 Two approaches: 两种方法:

One: 一:

const arrayOfObjectsToObjectOfArraysOfValues = items => {
  const newArrayOne = []
  const newArrayTwo = []
  const newArrayThree = []

  items.forEach(({ value1, value2, value3 }) => {
    newArrayOne.push(value1)
    newArrayTwo.push(value2)
    newArrayThree.push(value3)
  })

  return { newArrayOne, newArrayTwo, newArrayThree }
}

Two: 二:

const arrayOfObjectsToObjectOfArraysOfValues = items => ({
   newArrayOne: items.map(({ value1 }) => value1),
   newArrayTwo: items.map(({ value2 }) => value2),
   newArrayThree: items.map(({ value3 }) => value3),
})

Edit (There is also this option): 编辑(也有此选项):

const arrayOfObjectsToObjectOfArraysOfValues = items => {
  return items.reduce((r, { value1, value2, value3 }, i) => {
    r.newArrayOne[i] = value1;
    r.newArrayTwo[i] = value2;
    r.newArrayThree[i] = value3;
    return r;
  }, { newArrayOne: [], newArrayTwo: [], newArrayThree: [] });
}

Obviously the second one is more concise, but it can be criticized for doing three loops where only one is required. 显然,第二个循环更简洁,但是在只需要一个循环的情况下进行三个循环就可以批评它了。 On the other hand the first one is doing 3 operations per loop cycle. 另一方面,第一个循环每个循环执行3次操作。 The key question option is "which (or is there another more elegant) option (which) is most performant?" 关键问题选项是“哪个(或另一个更优雅)选项(哪个)表现最出色?”

Ok, I got on the jsperf bandwagon for my first time... looks like the answer here is it depends on the client: 好的,我是第一次上jsperf潮流……看起来答案就在这里,这取决于客户端:

https://jsperf.com/arrayofobjectstoobjectofarraysofvalues/1 https://jsperf.com/arrayofobjectstoobjectofarraysofvalues/1

On Firefox option 1 is 23% slower. 在Firefox上,选项1慢23%。 (832,000 ops per second baseline) (每秒832,000次基准操作)
On Chrome option 2 is 88% slower. 在Chrome上,选项2慢88%。 (248,000 ops per second baseline) (每秒248,000次基准操作)
On Safari option 2 is 48% slower. 在Safari上,选项2慢48%。 (158,000 ops per second baseline) (每秒158,000次操作基准)

Edit: reduce option is 2% slower in Chrome & Safari, but 50% slower in Firefox. 编辑:减少选项在Chrome和Safari中慢2%,但在Firefox中慢50%。

So, probably yes, option 1 is better in most cases. 因此,可能是的,在大多数情况下,选项1更好。 A pity for conciseness... Also, go Firefox - so fast! 为了简洁起见,还真可惜...另外,使用Firefox-太快了!

Finally, I suppose Option one can become a little conciser using reduce. 最后,我认为使用reduce可以使选项一变得简明扼要。

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

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