Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 140788

JavaScript - Exporting a harcoded array vs creating one

$
0
0

Let's say I have a file data.js, which contains an array of some data that will be imported somewhere (eg. a React component).

EXAMPLE A:

const DATA = [
  {
    firstName: 'jim',
    lastName: 'beam',
    fullName: 'jim beam'
  },
  {
    firstName: 'jack',
    lastName: 'daniels',
    fullName: 'jack daniels'
  }
];

export default DATA;

Ok, cool. Thing is, we're writing out the fullName property, which could be gathered by combining firstName and lastName. This is a very trivial example for clarity, so bear with me. We could also do something like this:

EXAMPLE B:

const DATA = [
  { firstName: 'jim', lastName: 'beam' },
  { firstName: 'jack', lastName: 'daniels' }
];

export default DATA.map(person => ({
   ...person,
   fullName: `${person.firstName} ${person.lastName}`
});

Heck, we could even do this!

EXAMPLE C:

const DATA = ['jim beam', 'jack daniels'];

export default DATA.map(person => {
  const [firstName, lastName] = person.split('');
  return {
    firstName,
    lastName,
    fullName: person
  };
};

So, imagine you have a huuge list of data, where multiple values could be derived from one initial value. My question is how would examples B and C differ from just hardcoding everything right off the bat like example A?

If you had hundreds of items, examples B and C could have much less overhead, a smaller file size, and can reduce potential typos... But, we're declaring an array and then exporting a different one, which I assume could have a performance dip? Thoughts?


Viewing all articles
Browse latest Browse all 140788

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>