// Из массива плоских данных преобразовать в структуру
 
const data = [
{ id: 1, age: 20, name: 'Иван', country: 'Russia', registered: true },
{ id: 2, age: 25, name: 'Колыван', country: 'Usa', registered: false },
{ id: 3, age: 30, name: 'Максим', country: 'Russia', registered: true },
{ id: 4, age: 50, name: 'Алёна', country: 'Usa', registered: true },
{ id: 5, age: 16, name: 'Никита', country: 'Usa', registered: false },
{ id: 6, age: 99, name: 'Макс', country: 'Russia', registered: true },
];
 
// const foo = (data, field, innerKey) => {
// return data.reduce((acc, current) => {
// const fieldByKey = current[field];
 
// if (!acc[fieldByKey]) {
// acc[fieldByKey] = {};
// }
 
// // Удаляем поле(поля), по которому мы будем складывать объект
// const innerKeyValue = current[innerKey];
// const rest = omit(current, 'id', 'age');
 
// acc[fieldByKey][innerKeyValue] = rest;
 
// return acc;
// }, {});
// };
 
// Omit для удаления ненужных полей
const omit = (obj, ...keys) => {
const filteredKeys = Object.keys(obj).filter(key => !keys.includes(key));
 
return filteredKeys.reduce((acc, key) => {
if (obj[key]) {
acc[key] = obj[key];
}
return acc;
}, {});
};
 
// Упрощённый вариант без Omita
 
const foo = (data, field) => {
return data.reduce((acc, current) => {
const fieldByKey = current[field];
 
if (!acc[fieldByKey]) {
acc[fieldByKey] = {};
}
 
const { id, ...rest } = current;
acc[fieldByKey][id] = rest;
 
return acc;
}, {});
};
 
console.log(foo(data, 'country', 'id'));
 
Code will run automatically after changes.
Code runs in an isolated environment.