Отображение массива объектов в словарь в машинописи - PullRequest
0 голосов
/ 23 апреля 2020

Я пытаюсь отобразить массив объектов в словарь, используя машинопись. Я написал следующий код:

let data = [
  {id: 1, country: 'Germany', population: 83623528},
  {id: 2, country: 'Austria', population: 8975552},
  {id: 3, country: 'Switzerland', population: 8616571}
];

let dictionary = Object.assign({}, ...data.map((x) => ({[x.id]: x.country})));

Я получаю вывод, как показано ниже:

{1: "Germany", 2: "Austria", 3: "Switzerland"}

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

let dictionary = Object.assign({}, ...data.map((x) => ({[x.id]: x.country, x.population})));

Требуемый вывод похож на ниже:

{
  "1": {
    "country": "Germany",
    "population": 83623528
  },
  "2": {
    "country": "Austria",
    "population": 8975552
  },
  "3": {
    "country": "Switzerland",
    "population": 8616571
  }
}

Ответы [ 3 ]

1 голос
/ 23 апреля 2020

Вы можете попробовать использовать Object.fromEntries (при условии, что ваше значение должно быть объектом для сохранения country и population):

let data = [
    {id: 1, country: 'Germany', population: 83623528},
    {id: 2, country: 'Austria', population: 8975552},
    {id: 3, country: 'Switzerland', population: 8616571}
];

let dictionary = Object.fromEntries(data.map(({id,...rest})=> ([id, rest]) ));

console.log(dictionary);

или в случае, если вы хотите вернуть массив без ключей:

let data = [
    {id: 1, country: 'Germany', population: 83623528},
    {id: 2, country: 'Austria', population: 8975552},
    {id: 3, country: 'Switzerland', population: 8616571}
];

let dictionary = Object.fromEntries(data.map(({id,...rest})=> ([id, Object.values(rest)]) ));

console.log(dictionary);
1 голос
/ 23 апреля 2020

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

let data = [
  {id: 1, country: 'Germany', population: 83623528},
  {id: 2, country: 'Austria', population: 8975552},
  {id: 3, country: 'Switzerland', population: 8616571}
];

let dictionary = Object.assign({}, ...data.map(({
  id,
  ...rest
}) => ({
  [id]: rest
})));

console.log(dictionary)
1 голос
/ 23 апреля 2020

Я думаю, вы прыгаете что-то вроде этого:

let data = [
  {id: 1, country: 'Germany', population: 83623528},
  {id: 2, country: 'Austria', population: 8975552},
  {id: 3, country: 'Switzerland', population: 8616571}
];

let dictionary = Object.fromEntries(data.map(item => [item.id, {country: item.country, population: item.population}]));

console.log(dictionary);
...