简体   繁体   中英

Benefits of using spread operator when iterating over an array of objects?

I seen this the other day in a solution that someone provided me on another question and I am just wondering what the benefits were of using the spread operator when iterating over an array of objects other than the obvious amount of code

 (function() { var junkData = [{ ID: 1, FirstName: "Abe", LastName: "Lincoln" }, { ID: 2, FirstName: "George", LastName: "Washington" }, { ID: 3, FirstName: "Donald", LastName: "Trump" }, { ID: 4, FirstName: "Ronald", LastName: "Reagan" } ]; for (let i = 0; i < junkData.length; i++) { console.log(junkData[i]); } console.log(""); for (let i = 0; i < junkData.length; i++) { const item = {...junkData[i] }; console.log(item); } })();

The only other benefit I see is, while looping,

That instead of using

junkData[i].FirstName

we can do

junkData.FirstName

You can use object spreading instead of Object.assign in order to create a shallow copy. This is to avoid mutating the source object if you want to follow an immutable approach, so you make a new copy and mutate the fields in the new copy only

The Rest/Spread Properties for ECMAScript proposal (ES2018) added spread properties to object literals. It copies own enumerable properties from a provided object onto a new object.

Shallow-cloning (excluding prototype) or merging of objects is now possible using a shorter syntax than Object.assign().

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

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