Skip to content

Instantly share code, notes, and snippets.

@oleggrishechkin
Last active May 27, 2021 16:39
Show Gist options
  • Save oleggrishechkin/86d7076ca5d69e3646bbcec9c554cfb5 to your computer and use it in GitHub Desktop.
Save oleggrishechkin/86d7076ca5d69e3646bbcec9c554cfb5 to your computer and use it in GitHub Desktop.

шаблон

// написать функцию, которая преобразует массив объектов в объект ключ-значение использую заданный id в качестве ключа

const normalize = (array, id) => {
  //код
};

const arr = [{ id: 1, title: 'object1' }, { id: 2, title: 'object2' }];

const result = normalize(arr, 'id');

console.log(result);
/*
{
  '1': { id: 1, title: 'object1' },
  '2': { id: 2, title: 'object2' }
};
*/

решение

const normalize = (array, id) => array.reduce((result, item) => {
  result[item[id]] = item;
  
  return result;
}, {});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment