Home > Software design >  How to sort object keys
How to sort object keys

Time:01-06

I currently have an object (configuration) that gets mapped over in order to display each item on a wrap up screen. However, I need to do a sort on the object before the map but am having trouble accessing the specific value that I need.

const ConfigComponentSummaryContainer = ({ configuration }) => (
    <Grid container spacing={4}>
      {Object.keys(configuration)
        .map(key => {
          const config = configuration[key];
          if (config && config.length && !restrictList.includes(config[0].component.grouping.toLowerCase())) {
            return config
              .map(c => (
                <Grid item xs={6} ref={componentRef}>
                  <ConfigComponentSummary configuration={c} />
                </Grid>
              ));
          }
          return null;
      })}
    </Grid>
  );

This is what the configuration object looks like in the console: enter image description here

I need to grab a value (seq) inside of component to use for the sort. How can I can access that specific value and sort before the keys are mapped?

CodePudding user response:

Use sort. You can use keys and look up the object like you do in map, or use entries where you get both the key and value.

Object.entries(configuration)
  .sort((a, b) => a[1][0].component.seq - b[1][0].component.seq)
  .map(([key, config]) => {}); 

CodePudding user response:

Only one data structure can be used for sorting, it is Array. I suppose you need to transform you object to array sorted by seq in component and then use it for mapping

CodePudding user response:

You can use lodash. It has a method sortBy which you should be able to use like this:

_.sortBy(configuration, "component.seq")
  •  Tags:  
  • Related