简体   繁体   中英

Sorting names into a specific order?

I have this object of student grade data, looks something like this

data = {
 9: {
  Math: {
   className: {
     grade: 'A'
   }
   className2: {
     grade: 'A'
   }
  }
  History: {
   className: {
     grade: 'A'
   }
   className2: {
     grade: 'A'
   }
  }
  English: {
   className: {
     grade: 'A'
   }
   className2: {
     grade: 'A'
   }
  }
 }
}

it goes from 9-12.

I was wondering if I could sort the Math/History/English part in a specific order, like I want English first then Math then History.

Thanks

Your data structure doesn't look the most suitable for what you want to achieve, but yes - you can order the object if you want to. Starting from ES2015, the order of object keys is granted, so having these school subjects in desired order makes some sense.

Try Array.prototype.reduce to achieve the desired order:

const subjects = ['English', 'Math', 'History'];

const orderedData = Object.entries(data).reduce((result, [n, nData]) => ({
    ...result,
    [n]: subjects.reduce((entry, subject) => ({
        ...entry,
        [subject]: nData[subject]
    }), {})
}), {});

// orderedData now contains new object in desired order

As Bergi already did point to, one has to restructure each class level's value from what is now an object structure into an array of subject (related) data ...

 const sampleData = { 9: { Math: { className: { grade: 'A' }, className2: { grade: 'A' } }, History: { className: { grade: 'A' }, className2: { grade: 'A' } }, English: { className: { grade: 'A' }, className2: { grade: 'A' } } }, 10: { Math: { className: { grade: 'A' } }, History: { className: { grade: 'A' } }, English: { className: { grade: 'A' } } } }; const subjectPrecedence = new Map( ['English', 'Math', 'History'].map((subject, idx) => [subject, idx]) ); function compareEntryKeysViaBoundPrecedenceMap(entryA, entryB) { return (this.get(entryA[0]) - this.get(entryB[0])); } function restructureClassEntry(collector, classEntry) { const { data, compareSubjectEntries } = collector; const [ classLevel, levelData ] = classEntry; data[classLevel] = Object .entries(levelData) .sort(compareSubjectEntries) .map(entry => Object.fromEntries([entry])); return collector; } const orderedClassData = Object .entries(sampleData) .reduce(restructureClassEntry, { compareSubjectEntries: compareEntryKeysViaBoundPrecedenceMap.bind(subjectPrecedence), data: {} }).data; console.log('[...subjectPrecedence.entries()] :', [...subjectPrecedence.entries()]); console.log('orderedClassData :', orderedClassData);
 .as-console-wrapper { min-height: 100%!important; top: 0; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM