In the first code, you're creating a new object for every iteration of .reduce
.
(在第一个代码中,您将为.reduce
每次迭代创建一个新对象。)
In certain engines, this may be slightly less efficient than your second code, which only creates a single object. (在某些引擎中,这可能比第二个代码(仅创建一个对象)的效率略低。)
(That said, efficiency rarely matters much; code clarity is much more important in most situations). ((也就是说,效率几乎没有多大意义;在大多数情况下,代码的清晰性更为重要)。)
But, for this situation, there's an even more suitable method to use when creating an object from an array, which avoids the slightly clunky syntax of reduce
:
(但是,对于这种情况,从数组创建对象时,还有一种更合适的方法可以使用,它避免了reduce
笨拙语法:)
const output = Object.fromEntries(
items.map(item => [item.id, item])
);
const items = [ { id: 5, val: 5 }, { id: 10, val: 10 }, { id: 15, val: 15 }, ]; const output = Object.fromEntries( items.map(item => [item.id, item]) ); console.log(output);
That said, keep in mind that Object.fromEntries
is a relatively new feature, so if this is meant for a public-facing website, make sure to include a polyfill.
(也就是说,请记住Object.fromEntries
是一个相对较新的功能,因此,如果这是面向面向公众的网站,请确保包含polyfill。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…