Skip to content
Advertisement

Typescript map specific columns from an array

I have an array of objects and I need a way to allow the user to select which properties they want to import in the database. Is there a way to map and create a separate array only with the properties the user actually wants to send insert.

For example, if we have the following array:

[
    {name: 'name1', address: 'addr1', phone: '123'},
    {name: 'name2', address: 'addr1', phone: '123'},
    {name: 'name3', address: 'addr1', phone: '123'},
    {name: 'name4', address: 'addr1', phone: '123'},
]

and the user selects name and phone only, then the array that is sent to be added in the database should look like this:

[
        {name: 'name1', phone: '123'},
        {name: 'name2', phone: '123'},
        {name: 'name3', phone: '123'},
        {name: 'name4', phone: '123'},
    ]

How can this be achieved?

Advertisement

Answer

Use map and return the new object

const arr = [
    {name: 'name1', address: 'addr1', phone: '123'},
    {name: 'name2', address: 'addr1', phone: '123'},
    {name: 'name3', address: 'addr1', phone: '123'},
    {name: 'name4', address: 'addr1', phone: '123'},
];

const res = arr.map(({name, phone}) => ({name, phone}));
console.log(res);

If you want to make it dynamic with an array of props to copy over

const arr = [
    {name: 'name1', address: 'addr1', phone: '123'},
    {name: 'name2', address: 'addr1', phone: '123'},
    {name: 'name3', address: 'addr1', phone: '123'},
    {name: 'name4', address: 'addr1', phone: '123'},
];

const copy = ['name', 'phone'];

const res = arr.map(data => copy.reduce((o, k) => (o[k] = data[k], o), {}));

console.log(res);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement