Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

javascript - 我应该避免在reduce中使用对象散布吗?(Should I avoid using object spread in reduce?)

Given the following example:

(给出以下示例:)

// option 1
items.reduce((values, item) => ({
     ...values,
     [item.id]: item.name
}), {})


// option 2
items.reduce((values, item) => {
    values[item.id] = item.name;
    return values;
}, {});

Is there a best practice pro or contra using object spread syntax in this case?

(在这种情况下,是否存在使用对象传播语法的最佳实践专家或反对者?)

  ask by guy mograbi translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...