Extracting key and array value from javascript object? [closed]

Posted on

Problem

My data looks like this:

const sleepStages = [
  {deep: Array(40)},
  {light: Array(40)},
  {rem: Array(40)},
  {awake: Array(40)},
]

I’m using the key and values separately and am using TypeScript.

sleepStages.flatMap((sleepStage) => {
  const stageName = Object.keys(sleepStage)[0];
  const stageValues = Object.values(sleepStage)[0];
  console.log(stageName, stageValues);
});

Does this approach make sense? Whenever I type [0] it smells.

Solution

A more concise approach would be to use Object.entries to get the 0th key and value at once:

const [stageName, stageValues] = Object.entries(sleepStage)[0];

Yes, the [0] looks weird, but unless you know the keys and/or in advance, you have to use a method which iterates over them, and then you need to extract the first item. In Javascript, there’s no good way of avoiding the [0] – there’s nothing like Object.prototype.getFirstEntry.

You could nest the destructuring on the left side, but that looks much less readable IMO:

const [[stageName, stageValues]] = Object.entries(sleepStage);

Ideally, in this sort of situation, you would fix the input data so that the keys are predictable and static:

const sleepStages = [
  { name: 'deep', values: Array(40) },
  { name: 'light', values: Array(40) },
  { name: 'rem', values: Array(40) },
  { name: 'awake', values: Array(40) },
]

Then, in the loop, you could do:

const { name, values } = sleepStage;

Leave a Reply

Your email address will not be published. Required fields are marked *