Свойства объекта заказа Javascript, основанные на определенном значении - PullRequest
0 голосов
/ 24 мая 2018

У меня есть две части данных, с которыми я работаю, чтобы в конечном итоге сгенерировать таблицу HTML.

Данные: Это основные данные, которые будут получены при обращении к базе данных.

UserColumns: Определяет, в каком порядке будут столбцы таблицы. fieldSource в этом объекте будет совпадать с именами ключей в объекте data.

// Define the core data we will be working with. Assumed this comes from a database,
var data = [{
    FirstName: 'Joe',
    LastName: 'Jones',
    Age: 21,
    Location: 'Arizona',
    Color: 'Red', // Not defined in the column structure, therefore is not included in output
    Order: 1
  },
  {
    FirstName: 'Tim',
    LastName: 'Bob',
    Age: 25,
    Location: 'California',
    Color: 'Blue',
    Order: 3
  },
  {
    FirstName: 'Sally',
    LastName: 'Smith',
    Age: 29,
    Location: 'Florida',
    Color: 'Green',
    Order: 2
  }
];

// Defines the columns the user wants to include in their table output as well as their order
var userColumns = [{
    FieldID: 1,
    FieldSource: 'FirstName',
    FieldName: 'First Name',
    Order: 2
  },
  {
    FieldID: 2,
    FieldSource: 'LastName',
    FieldName: 'Last Name',
    Order: 1
  },
  {
    FieldID: 3,
    FieldSource: 'Age',
    FieldName: 'Age',
    Order: 4
  },
  {
    FieldID: 4,
    FieldSource: 'Location',
    FieldName: 'Location',
    Order: 3
  }
];

/*
    Loop over the data and order the content in the desired column order.
*/
function generateTableRows() {

  let output = [];

  for (var j = 0; j < data.length; j++) {
    // Need to re-order the object keys based on the "User Columns".
    // This also needs to ensure the the table rows are in the correct order based on the "Order" property
    console.log(data[j]);
  }

}

В приведенном выше примере кода keys в data необходимо переупорядочить в соответствии с порядком, определенным в объекте userColumns.

Конечной целью здесь является то, что пользователь увидиттаблица данных в желаемом виде (столбцы в заданном порядке).

Как можно расположить ключи в определенном порядке, и они останутся такими же в объекте или они могут измениться?

Мне нужно, по сути, взять объект данных, а затем вывести его так, чтобы он находился в определенном пользователем порядке, когда наступает время для рендеринга таблицы.

Вот скрипка полной задачипод рукой я пытаюсь тренировки: https://jsfiddle.net/os48s1ne/

1 Ответ

0 голосов
/ 24 мая 2018

Сортируйте свойство userColumns, затем пройдитесь по нему и используйте свойства FieldSource для доступа к соответствующим свойствам в данных.

/*
    Loop over the data and order the content in the desired column order.
*/
function generateTableRows() {
  userColumns.sort((a, b) => a.Order - b.Order);
  let output = data.map(d => userColumns.map(({
    FieldSource,
    FieldName
  }) => `${FieldName} = ${d[FieldSource]}`).join(', '));
  console.log(output);
}

// Define the core data we will be working with. Assumed this comes from a database,
var data = [{
    FirstName: 'Joe',
    LastName: 'Jones',
    Age: 21,
    Location: 'Arizona',
    Color: 'Red', // Not defined in the column structure, therefore is not included in output
    Order: 1
  },
  {
    FirstName: 'Tim',
    LastName: 'Bob',
    Age: 25,
    Location: 'California',
    Color: 'Blue',
    Order: 3
  },
  {
    FirstName: 'Sally',
    LastName: 'Smith',
    Age: 29,
    Location: 'Florida',
    Color: 'Green',
    Order: 2
  }
];

// Defines the columns the user wants to include in their table output as well as their order
var userColumns = [{
    FieldID: 1,
    FieldSource: 'FirstName',
    FieldName: 'First Name',
    Order: 2
  },
  {
    FieldID: 2,
    FieldSource: 'LastName',
    FieldName: 'Last Name',
    Order: 1
  },
  {
    FieldID: 3,
    FieldSource: 'Age',
    FieldName: 'Age',
    Order: 4
  },
  {
    FieldID: 4,
    FieldSource: 'Location',
    FieldName: 'Location',
    Order: 3
  }
];



generateTableRows();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...