Группировать массив данных по имени - PullRequest
0 голосов
/ 28 января 2019

Я пытаюсь разработать массив с опытом «Транспорт», содержащий каждый сектор и присвоенный им текст.

Вот что у меня есть:


    - Healthcare
    -- Data-driven insights to improve healthcare
    -- Novel data mining and visualisation
    -- Human-centred augmented and virtual realities

    - Energy
    -- Urban Analytics
    -- Understanding patterns of consumer behaviour
    -- Optimising energy systems

Вот чтоЯ пытаюсь сделать:


    - expertise (e.g Transport)

    -- sector (e.g Data)
    --- text (e.g Urban Analytics)
    --- text (e.g Understanding patterns of consumer behaviour)
    --- text (e.g Human-centred augmented and virtual realities)

    -- sector (e.g Engineering)
    --- text (e.g Optimising energy systems)
    --- text (e.g High speed rail and system integration innovation)
    --- text (e.g Human-centred robotic and autonomous systems)
    --- text (e.g Surface engineering across the length scales)

    -- sector (e.g Environment)
    --- text (e.g Europe’s leading city simulation capability)

    - expertise
    -- sector
    --- text

Вот код, который я использую в данный момент, если кто-то может помочь, я был бы очень признателен.

var items = [{
    "item": {
      "id": 0,
      "sector": 'Data',
      "expertise": ["Healthcare"],
      "text": "Data-driven insights to improve healthcare"
    }
  },
  {
    "item": {
      "id": 1,
      "sector": 'Data',
      "expertise": ["Energy", "Transport", "Cities"],
      "text": "Urban Analytics"
    }
  },
  {
    "item": {
      "id": 2,
      "sector": 'Data',
      "expertise": ["Energy", "Transport", "Consumer"],
      "text": "Understanding patterns of consumer behaviour"
    }
  },
  {
    "item": {
      "id": 3,
      "sector": 'Data',
      "expertise": ["Healthcare", "Consumer"],
      "text": "Novel data mining and visualisation"
    }
  },
  {
    "item": {
      "id": 4,
      "sector": 'Data',
      "expertise": ["Healthcare", "Transport", "Consumer"],
      "text": "Human-centred augmented and virtual realities"
    }
  },
  {
    "item": {
      "id": 5,
      "sector": 'Healthcare',
      "expertise": ["Healthcare"],
      "text": "Medical technology innovation, translation and convergence"
    }
  },
  {
    "item": {
      "id": 6,
      "sector": 'Healthcare',
      "expertise": ["Healthcare"],
      "text": "Understanding cardio metabolic disease"
    }
  },
  {
    "item": {
      "id": 7,
      "sector": 'Healthcare',
      "expertise": ["Healthcare"],
      "text": "Improving early cancer diagnosis and treatment"
    }
  },
  {
    "item": {
      "id": 8,
      "sector": 'Healthcare',
      "expertise": ["Healthcare", "Pharmaceuticals"],
      "text": "Understanding life in molecular detail"
    }
  },
  {
    "item": {
      "id": 9,
      "sector": 'Healthcare',
      "expertise": ["Healthcare"],
      "text": "Evidencing treatment through clinical trials"
    }
  },
  {
    "item": {
      "id": 10,
      "sector": 'Engineering',
      "expertise": ["Energy", "Transport"],
      "text": "Optimising energy systems"
    }
  },
  {
    "item": {
      "id": 11,
      "sector": 'Engineering',
      "expertise": ["Energy"],
      "text": "Enhancing petroleum recovery"
    }
  },
  {
    "item": {
      "id": 12,
      "sector": 'Engineering',
      "expertise": ["Transport"],
      "text": "High speed rail and system integration innovation"
    }
  },
  {
    "item": {
      "id": 13,
      "sector": 'Engineering',
      "expertise": ["Healthcare", "Electronics"],
      "text": "Terahertz frequency electronic and photonic devices"
    }
  },
  {
    "item": {
      "id": 14,
      "sector": 'Engineering',
      "expertise": ["Healthcare", "Transport", "Manufacturing"],
      "text": "Human-centred robotic and autonomous systems"
    }
  },
  {
    "item": {
      "id": 15,
      "sector": 'Engineering',
      "expertise": ["Healthcare", "Energy", "Transport", "Manufacturing"],
      "text": "Surface engineering across the length scales"
    }
  },
  {
    "item": {
      "id": 16,
      "sector": 'Engineering',
      "expertise": ["Pharmaceuticals", "Manufacturing"],
      "text": "Chemical and process engineering from molecule to product"
    }
  },
  {
    "item": {
      "id": 17,
      "sector": 'Engineering',
      "expertise": ["Pharmaceuticals"],
      "text": "Bionanotechnology for disease diagnosis, treatment and prevention"
    }
  },
  {
    "item": {
      "id": 18,
      "sector": 'Engineering',
      "expertise": ["Healthcare", "Pharmaceuticals", "Electronics", "Manufacturing"],
      "text": "Engineering materials at the atomic level"
    }
  },
  {
    "item": {
      "id": 19,
      "sector": 'Environment',
      "expertise": ["Healthcare", "Environment & Food"],
      "text": "Addressing global challenges in food security"
    }
  },
  {
    "item": {
      "id": 20,
      "sector": 'Environment',
      "expertise": ["Healthcare", "Environment & Food"],
      "text": "Interdisciplinary approaches to tackling major water issues"
    }
  },
  {
    "item": {
      "id": 21,
      "sector": 'Environment',
      "expertise": ["Cities"],
      "text": "Designing cities of the future"
    }
  },
  {
    "item": {
      "id": 22,
      "sector": 'Environment',
      "expertise": ["Transport", "Cities"],
      "text": "Europe’s leading city simulation capability"
    }
  },
  {
    "item": {
      "id": 23,
      "sector": 'Environment',
      "expertise": ["Environment & Food"],
      "text": "Robust and timely climate solutions"
    }
  }
];

let expertise;
let res = items.reduce((acc, {
  item: {
    expertise,
    text
  }
}) => {
  expertise.forEach(x => acc[x] = [...(acc[x] || []), text]);
  return acc;
}, {});


Object.entries(res).forEach(([k, v]) => {
  console.log(k + "\n->" + v.join("\n->"));
});

Ответы [ 2 ]

0 голосов
/ 28 января 2019

Вы можете попробовать следующий подход, который является общим:

Идея

  • Создать функцию ( скажем A ), которая печатает:
    • Bullet, в этом решении -
    • Используемая клавиша
    • значение этой клавиши в определенном формате.
  • Также создайте функцию ( скажем, B ), который анализирует и возвращает отформатированную строку для значения.
    • Для массива он будет использовать Array.join
    • Для непустых объектов он будет использовать ту же функцию, которую вы создали выше ( A ).
    • Для непустых литеральных значений возвращается value.toString()
    • А для пустых значений возвращается пустое значение.

  • Обе функции A и B обозначают нижний / следующий уровень.Следовательно, вам нужно будет добавить - или значение маркера к существующей строке маркера.
  • Поскольку это вложенная структура, вам придется очистить строку ( Удалить лишние \n s с помощью string.trim()), чтобы вы не получили несколько новых строк.
  • Использование этих взаимосвязанных функций приведет к печати в необходимом формате независимо от глубины.

function isEmpty(value) {
  return value === null || value === undefined
}

function getValueString(v, preString) {
  preString = `\n${preString.trim()}-`;
  return Array.isArray(v) && (preString + v.join(preString)) ||
    typeof v === 'object' && nestedLevelToString(v, preString) ||
    isEmpty(v) && v.toString() ||
    '';
}

function nestedLevelToString(data, preString) {
  preString = preString || '-';
  let output = ''
  for (const key in data) {
    output += `${preString}${key}${getValueString(data[key], preString)}`;
  }
  return output;
}

var items = [{"item": {"id": 0,"sector": 'Data',"expertise": ["Healthcare"],"text": "Data-driven insights to improve healthcare"}},{"item": {"id": 1,"sector": 'Data',"expertise": ["Energy", "Transport", "Cities"],"text": "Urban Analytics"}},{"item": {"id": 2,"sector": 'Data',"expertise": ["Energy", "Transport", "Consumer"],"text": "Understanding patterns of consumer behaviour"}},{"item": {"id": 3,"sector": 'Data',"expertise": ["Healthcare", "Consumer"],"text": "Novel data mining and visualisation"}},{"item": {"id": 4,"sector": 'Data',"expertise": ["Healthcare", "Transport", "Consumer"],"text": "Human-centred augmented and virtual realities"}},{"item": {"id": 5,"sector": 'Healthcare',"expertise": ["Healthcare"],"text": "Medical technology innovation, translation and convergence"}},{"item": {"id": 6,"sector": 'Healthcare',"expertise": ["Healthcare"],"text": "Understanding cardio metabolic disease"}},{"item": {"id": 7,"sector": 'Healthcare',"expertise": ["Healthcare"],"text": "Improving early cancer diagnosis and treatment"}},{"item": {"id": 8,"sector": 'Healthcare',"expertise": ["Healthcare", "Pharmaceuticals"],"text": "Understanding life in molecular detail"}},{"item": {"id": 9,"sector": 'Healthcare',"expertise": ["Healthcare"],"text": "Evidencing treatment through clinical trials"}},{"item": {"id": 10,"sector": 'Engineering',"expertise": ["Energy", "Transport"],"text": "Optimising energy systems"}},{"item": {"id": 11,"sector": 'Engineering',"expertise": ["Energy"],"text": "Enhancing petroleum recovery"}},{"item": {"id": 12,"sector": 'Engineering',"expertise": ["Transport"],"text": "High speed rail and system integration innovation"}},{"item": {"id": 13,"sector": 'Engineering',"expertise": ["Healthcare", "Electronics"],"text": "Terahertz frequency electronic and photonic devices"}},{"item": {"id": 14,"sector": 'Engineering',"expertise": ["Healthcare", "Transport", "Manufacturing"],"text": "Human-centred robotic and autonomous systems"}},{"item": {"id": 15,"sector": 'Engineering',"expertise": ["Healthcare", "Energy", "Transport", "Manufacturing"],"text": "Surface engineering across the length scales"}},{"item": {"id": 16,"sector": 'Engineering',"expertise": ["Pharmaceuticals", "Manufacturing"],"text": "Chemical and process engineering from molecule to product"}},{"item": {"id": 17,"sector": 'Engineering',"expertise": ["Pharmaceuticals"],"text": "Bionanotechnology for disease diagnosis, treatment and prevention"}},{"item": {"id": 18,"sector": 'Engineering',"expertise": ["Healthcare", "Pharmaceuticals", "Electronics", "Manufacturing"],"text": "Engineering materials at the atomic level"}},{"item": {"id": 19,"sector": 'Environment',"expertise": ["Healthcare", "Environment & Food"],"text": "Addressing global challenges in food security"}},{"item": {"id": 20,"sector": 'Environment',"expertise": ["Healthcare", "Environment & Food"],"text": "Interdisciplinary approaches to tackling major water issues"}},{"item": {"id": 21,"sector": 'Environment',"expertise": ["Cities"],"text": "Designing cities of the future"}},{"item": {"id": 22,"sector": 'Environment',"expertise": ["Transport", "Cities"],"text": "Europe’s leading city simulation capability"}},{"item": {"id": 23,"sector": 'Environment',"expertise": ["Environment & Food"],"text": "Robust and timely climate solutions"}}];


let expertise;
const res = {};
res['sector'] = items.reduce((acc, {
  item: {
    expertise,
    text
  }
}) => {
  expertise.forEach(x => acc[x] = [...(acc[x] || []), text]);
  return acc;
}, {});

console.log(nestedLevelToString(res));
0 голосов
/ 28 января 2019

Вам нужен еще один уровень для секторов:

var items = [{"item": {"id": 0,"sector": 'Data',"expertise": ["Healthcare"],"text": "Data-driven insights to improve healthcare"}},{"item": {"id": 1,"sector": 'Data',"expertise": ["Energy", "Transport", "Cities"],"text": "Urban Analytics"}},{"item": {"id": 2,"sector": 'Data',"expertise": ["Energy", "Transport", "Consumer"],"text": "Understanding patterns of consumer behaviour"}},{"item": {"id": 3,"sector": 'Data',"expertise": ["Healthcare", "Consumer"],"text": "Novel data mining and visualisation"}},{"item": {"id": 4,"sector": 'Data',"expertise": ["Healthcare", "Transport", "Consumer"],"text": "Human-centred augmented and virtual realities"}},{"item": {"id": 5,"sector": 'Healthcare',"expertise": ["Healthcare"],"text": "Medical technology innovation, translation and convergence"}},{"item": {"id": 6,"sector": 'Healthcare',"expertise": ["Healthcare"],"text": "Understanding cardio metabolic disease"}},{"item": {"id": 7,"sector": 'Healthcare',"expertise": ["Healthcare"],"text": "Improving early cancer diagnosis and treatment"}},{"item": {"id": 8,"sector": 'Healthcare',"expertise": ["Healthcare", "Pharmaceuticals"],"text": "Understanding life in molecular detail"}},{"item": {"id": 9,"sector": 'Healthcare',"expertise": ["Healthcare"],"text": "Evidencing treatment through clinical trials"}},{"item": {"id": 10,"sector": 'Engineering',"expertise": ["Energy", "Transport"],"text": "Optimising energy systems"}},{"item": {"id": 11,"sector": 'Engineering',"expertise": ["Energy"],"text": "Enhancing petroleum recovery"}},{"item": {"id": 12,"sector": 'Engineering',"expertise": ["Transport"],"text": "High speed rail and system integration innovation"}},{"item": {"id": 13,"sector": 'Engineering',"expertise": ["Healthcare", "Electronics"],"text": "Terahertz frequency electronic and photonic devices"}},{"item": {"id": 14,"sector": 'Engineering',"expertise": ["Healthcare", "Transport", "Manufacturing"],"text": "Human-centred robotic and autonomous systems"}},{"item": {"id": 15,"sector": 'Engineering',"expertise": ["Healthcare", "Energy", "Transport", "Manufacturing"],"text": "Surface engineering across the length scales"}},{"item": {"id": 16,"sector": 'Engineering',"expertise": ["Pharmaceuticals", "Manufacturing"],"text": "Chemical and process engineering from molecule to product"}},{"item": {"id": 17,"sector": 'Engineering',"expertise": ["Pharmaceuticals"],"text": "Bionanotechnology for disease diagnosis, treatment and prevention"}},{"item": {"id": 18,"sector": 'Engineering',"expertise": ["Healthcare", "Pharmaceuticals", "Electronics", "Manufacturing"],"text": "Engineering materials at the atomic level"}},{"item": {"id": 19,"sector": 'Environment',"expertise": ["Healthcare", "Environment & Food"],"text": "Addressing global challenges in food security"}},{"item": {"id": 20,"sector": 'Environment',"expertise": ["Healthcare", "Environment & Food"],"text": "Interdisciplinary approaches to tackling major water issues"}},{"item": {"id": 21,"sector": 'Environment',"expertise": ["Cities"],"text": "Designing cities of the future"}},{"item": {"id": 22,"sector": 'Environment',"expertise": ["Transport", "Cities"],"text": "Europe’s leading city simulation capability"}},{"item": {"id": 23,"sector": 'Environment',"expertise": ["Environment & Food"],"text": "Robust and timely climate solutions"}}];

const res = items.reduce((acc, {item: {sector, expertise, text}}) => {
    expertise.forEach(exp => {
        acc[exp] = acc[exp] || {};
        acc[exp][sector] = [...(acc[exp][sector] || []), text];
    });
    return acc;
}, {});

Object.entries(res).forEach(([exp, sectors]) => {
    console.log("- " + exp);
    Object.entries(sectors).forEach(([sector, texts]) => {
        console.log("-- " + sector + "\n--- " + texts.join("\n--- "));
    });
});

Пояснение

В операции reduce sector также захватывается с объекта.Как и в оригинале, экспертизы повторяются, но теперь объект acc становится двухуровневым, а не одним уровнем.Свойства первого уровня - это экспертизы (exp).Если такого свойства еще не существует, оно получает пустой объект в качестве значения:

        acc[exp] = acc[exp] || {};

Следующая строка очень похожа на то, что у вас уже было: следующий уровень свойства состоит из секторов и для каждого сектораподдерживается массив текстов.

Во второй части кода применяется тот же принцип, что у вас уже был, но опять же с дополнительным уровнем.Сначала проверяются свойства экспертизы.Они имеют объекты в качестве значений, каждый из которых имеет свойства сектора.Внутренний цикл снова очень похож на ваш: для каждого сектора отображаются сектор и связанные с ним текстовые значения.

...