I am considering the below two approaches for building an array of objects:
Approach 1 (list all properties, even if duplicated among objects):
const employees = [
{
company: 'ABC',
country: 'IN',
zip: 123,
employeeId: 123,
employeeName: 'p'
},
{
company: 'ABC',
country: 'IN',
zip: 123,
employeeId: 456,
employeeName: 'q'
},
{
company: 'ABC',
country: 'IN',
zip: 123,
employeeId: 789,
employeeName: 'r'
}
];
Approach 2 (avoid duplication with the spread operator):
const commonParams = {
company: 'ABC',
country: 'IN',
zip: 123
};
const employees = [
{
...commonParams,
employeeId: 123,
employeeName: 'p'
},
{
...commonParams,
employeeId: 456,
employeeName: 'q'
},
{
...commonParams,
employeeId: 789,
employeeName: 'r'
}
]
Approach 2 is more succint, and adding a new property that is common to all array elements would be much easier (and less prone to errors).
However, in case of a large commonParams
object, does approach 2 (using the spread operator) affect performance as compared to approach 1?
Would the spread operator loop through each of the properties of the commonParams
object for each of the objects in the employees
array?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…