vitaly-t
vitaly-t

Reputation: 25840

Fastest property injection in JavaScript?

I have an array of property names = ['prop1', 'prop2',...].

And I need to inject them as standard properties into object obj, without specifying any values, i.e. undefined.

What is the most efficient/performant way to do that?

And would it make any difference when creating obj with only those properties somehow?

Upvotes: 0

Views: 343

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074435

I expect your fastest option will be a simple for loop running backward to 0:

let obj = {};
for (let i = array.length - 1; i >= 0; --i) {
    obj[array[i]] = undefined;
}

But unless you've run into a real-world performance problem, it's likely to be premature optimization.

Upvotes: 2

Related Questions