Фильтровать мой массив / JSON Данные (включая несколько значений) на основе нескольких критериев в JavaScript? - PullRequest
0 голосов
/ 19 февраля 2020

Сложная часть здесь:

  • Некоторые содержат более 1 значения (например, активные вещества: ["Морфин", "Фентанил"])
  • Некоторые значения повторяются ( ретроспектива: "1" для "true"; ward_focused: "1" для true (снова))

Так что предыдущие решения здесь не работали для моего проекта.

jsonData

[
 {
  "title": "Real-world evidence of high-cost drugs for metastatic melanoma",
  "url": "https://.../Suppl_1/A5.1",
  "filters": {
    "retrospective": "1",
    "ward_focused": "2",
    "indication_focused": "1",
    "active_substance": "2"
  }
 },
 {
  "title": "Real-world safety and tolerability of the recently commercialised palbociclib",
  "url": "https://.../Suppl_1/A223.2",
  "filters": {
    "retrospective": "2",
    "ward_focused": "1",
    "indication_focused": "2",
    "active_substance": "Palbociclib"
  }
 },
 {
  "title": "Cost-effectiveness of morphine versus fentanyl in managing ventilated neonates",
  "url": "https://.../Suppl_1/A7.3",
  "filters": {
    "retrospective": "1",
    "ward_focused": "1",
    "indication_focused": "1",
    "active_substance": ["Morphine", "Fentanyl"]
  }
 },
 {
  "title": "Chemical risk assessement in a quality control laboratory",
  "url": "https://.../Suppl_1/A9.2",
  "filters": {
    "retrospective": "2",
    "ward_focused": "2",
    "indication_focused": "2",
    "active_substance": "2"
  }
 },
 {
  "title": "The economic burden of metastatic breast cancer in Spain",
  "url": "https://.../27/1/19",
  "filters":{
    "retrospective": "1",
    "ward_focused": "1",
    "indication_focused": "1",
    "active_substance": "2"
  }
 }
]

query

const selectedFilters = {
      retrospective: ["1"],
      ward_focused: ["2"],
      indication_focused: ["1"],
      active_substance: []
  };

Самое близкое решение было, когда я преобразовал свои данные в массив и работал с ним как:

  const filterArr = Object.values(selectedFilters).flat();

  const output = myDataArray.filter(({filters}) => {
      const objFilters = Object.values(filters).flat();
      return filterArr.every(val => objFilters.includes(val));
  })
  console.log(output);

НО это не удалось по той причине, что «1», «истина» и «2» для «ложь» повторяются много раз в каждом профиле.

Я открыт для работать как с JSON, так и с массивом для моих данных. Также я могу изменить структуру «1» - «2» для моих логических типов данных. Вы также можете изменить структуру данных, если необходимо, удалив детали «фильтры» и работающие на одну глубину.

Любая помощь заметна. С уважением

1 Ответ

2 голосов
/ 20 февраля 2020

Приведенный ниже фрагмент должен фильтровать ваши данные, используя функцию фильтра js и проверяя каждый возможный фильтр по фильтрам obj

const json =[
 {
  "title": "Real-world evidence of high-cost drugs for metastatic melanoma",
  "url": "https://.../Suppl_1/A5.1",
  "filters": {
    "retrospective": "1",
    "ward_focused": "2",
    "indication_focused": "1",
    "active_substance": "2"
  }
 },
 {
  "title": "Real-world safety and tolerability of the recently commercialised palbociclib",
  "url": "https://.../Suppl_1/A223.2",
  "filters": {
    "retrospective": "2",
    "ward_focused": "1",
    "indication_focused": "2",
    "active_substance": "Palbociclib"
  }
 },
 {
  "title": "Cost-effectiveness of morphine versus fentanyl in managing ventilated neonates",
  "url": "https://.../Suppl_1/A7.3",
  "filters": {
    "retrospective": "1",
    "ward_focused": "1",
    "indication_focused": "1",
    "active_substance": ["Morphine", "Fentanyl"]
  }
 },
 {
  "title": "Chemical risk assessement in a quality control laboratory",
  "url": "https://.../Suppl_1/A9.2",
  "filters": {
    "retrospective": "2",
    "ward_focused": "2",
    "indication_focused": "2",
    "active_substance": "2"
  }
 },
 {
  "title": "The economic burden of metastatic breast cancer in Spain",
  "url": "https://.../27/1/19",
  "filters":{
    "retrospective": "1",
    "ward_focused": "1",
    "indication_focused": "1",
    "active_substance": "2"
  }
 }
];
function filterJson(filterObj) {
  let hasRetrospective = false,
    hasWardFocused = false,
    hasIndicationFocused = false,
    hasActiveSubstance = false;
  const arr = json.filter(function (j) {
    hasRetrospective = filterObj.retrospective.indexOf(j.filters.retrospective) > -1;
    hasWardFocused = filterObj.ward_focused.indexOf(j.filters.ward_focused) > -1;
    hasIndicationFocused = filterObj.indication_focused.indexOf(j.filters.indication_focused) > -1;
    hasActiveSubstance = Array.isArray(j.filters.active_substance) ?    
      j.filters.active_substance.some(function (jf) {
        return filterObj.active_substance.indexOf(jf) > -1;
      }):
      filterObj.active_substance.indexOf(j.filters.active_substance) > -1;
    return hasRetrospective && hasWardFocused && hasIndicationFocused && hasActiveSubstance;
  }); 
  console.log(arr);
}
filterJson({
    retrospective: ["1"],
    ward_focused: ["1"],
    indication_focused: ["1"],
    active_substance: ["Morphine", "Fentanyl"]
});
...