Home > Software design >  Which is the best approach to push an object into an array? - push(obj) or push(JSON.parse(JSON.stri
Which is the best approach to push an object into an array? - push(obj) or push(JSON.parse(JSON.stri

Time:12-23

There is a users: any[] = [] array in my angular code which will be filled up dynamically with the person objects.

someMethod.subscribe((user) => {
  this.users.push(user);
})

But one of my colleagues preferred the below approach to push the object

someMethod.subscribe((user) => {
  this.users.push(JSON.parse(JSON.stringify(user)));
})

May I know - which would be the best approach & why?

CodePudding user response:

The former. The latter is sometimes used to deep-clone an object, but if you're not modifying the objects in the array, there's no need. And it also carries some risks: you can lose some data that's not available in JSON, such as functions, regex, symbols, and undefined; you could end up with some altered data, like NaN becoming null, and it'll mess with dates depending on the date format. It's also slow (compared to methods from utility libraries): Financial Times did a writeup on their tech blog in 2018 showing that having a JSON.parse(JSON.stringify(... on the data returned from every request slowed their site down by 10 times.

If you do need to clone the objects before pushing them, you could use a library like Lodash, or use push({...user}), depending on your exact needs.

  • Related