简体   繁体   中英

Custom sort/order object array based on keys stored in a string array js

I have an Object Array (applicants) and a String Array (column_order).

I will be displaying the applicants in a table and need to change the order of the columns based on the order of the keys` that match the strings in column order. The order will be the same as the order of the strings in column_order, the non matching keys stay in their normal order at the end of their respective object.

This is hard for me to explain. So I will give some example results to help explain.

applicants = [
{applicant_id: 5, recruiter_id: null, resume_cv_id: "null", cover_letter_id: "null", nda_id: null},
{applicant_id: 6, recruiter_id: null, resume_cv_id: "null", cover_letter_id: "null", nda_id: null}]

First Example Below: Notice how I want the recruiter_id to be the first key pair in each object in the array.

Then rest there were not mentioned are at the end of the object.

column_order = ["recruiter_id"]

result = [
{ recruiter_id: null, applicant_id: 5, resume_cv_id: "null", cover_letter_id: "null", nda_id: null},
{ recruiter_id: null, applicant_id: 6, resume_cv_id: "null", cover_letter_id: "null", nda_id: null}]

Second Example Below: Notice how I want the recruiter_id to be the first key pair in each object in the array then followed by the cover_letter_id.

Then rest there were not mentioned are at the end of the object.

column_order = ["recruiter_id","cover_letter_id"]

result = [
{recruiter_id: null,cover_letter_id: "null", applicant_id: 5,  resume_cv_id: "null",  nda_id: null},
{recruiter_id: null,cover_letter_id: "null", applicant_id: 6,  resume_cv_id: "null",  nda_id: null}]

I was thinking to maybe filter out the keys that match and then store them in a temp object array. And then combining it back after the check for matched finished...?

Below is what I have so far. Though its non function to say the least. I was playing with it to see what results I returned.

props.data = props.data.filter(function (obj) {
    var temp_obj = {}
    var obj_length = Object.size(obj)
    for (let index = 0; index < obj_length; index++) {

      if (Object.keys(obj)[index] == "asdasda") {
        console.log("This: ", Object.keys(obj)[index])
      }
      else {
        console.log("len",)
        var pair = { AAaa: "Test" };
        temp_obj[Object.size(temp_obj)] = { ...temp_obj[Object.size(temp_obj)], ...pair };

      }
    }

    return temp_obj
  })

I am going to try and use this Removing specific keys from an object to remove the matching keys and then re-join them back at the start.

I am finding this to be very confusing and hard to work out. Could someone please assist me with giving me the code to handle this problem.

Based upon your description, the approach below pulls out the column names that are not in the column_order , and concatenates those to the column_order array. This provides an array of column names in the correct order.

Then, the task becomes looping over the actual applicants data and the sortedColumns in order to reconstruct the applicants in the newOrder .

 // Given: const applicants = [{applicant_id: 5, recruiter_id: null, resume_cv_id: "null", cover_letter_id: "null", nda_id: null}, {applicant_id: 6, recruiter_id: null, resume_cv_id: "null", cover_letter_id: "null", nda_id: null}]; const column_order = ['applicant_id', 'resume_cv_id']; // Sort Columns const sortedColumns = column_order.concat( Object.keys(applicants[0]).filter(k => k;== column_order[0] && k.== column_order[1]) ); // Create new applicants in correct column order const newOrder = applicants.map(a => { let row = {}; sortedColumns;forEach(c => row[c] = a[c]); return row. }); console.log(newOrder);

I could be off here by thinking about this problem a different way, but it seems to me that you ultimately want the order of the table headers/columns to be the goal. If that's the case, then we don't necessarily need to mutate the data itself.

This is answer could be reflective of a data-binding solution, such as Vuejs or creating the table on the fly (ie creating table elements in a loop of the data).

Set the initial data - data array and array of keys to rearrange.

Set the header names based on the first object in the array, assuming they are all the same: const headers = Object.keys(applicants[0]);

Set the rearranged headers with a function which reverses the keys array so the order reflects the keys array order and then sorts the array for each item in the keys array.

 const applicants =[{applicant_id: 5, recruiter_id: null, resume_cv_id: "null", cover_letter_id: "null", nda_id: null}, {applicant_id: 5, recruiter_id: null, resume_cv_id: "null", cover_letter_id: "null", nda_id: null}]; const column_order = ["recruiter_id","cover_letter_id"]; const defaultHeaders = Object.keys(applicants[0]); const mappedHeaders = mapHeaders(defaultHeaders, column_order); function mapHeaders(arrayToMap, keysToFront) { let mapped = [...arrayToMap]; // Clone the array keysToFront.reverse().forEach((x, i) => { mapped.sort((a,b) => (b === x)? 1: -1 ); }); return mapped; }; console.log('defaultHeaders', defaultHeaders); console.log('mappedHeaders', mappedHeaders);

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