R
R
Roman2021-01-04 18:53:48
Node.js
Roman, 2021-01-04 18:53:48

How to merge (update) object properties using Nestjs?

Hello, there are those who worked with Nest.js? How can you freeze the values ​​of an old object with new values ​​(which came from the client), if, for example, you need to overwrite only those values ​​that have changed, and not the entire object? I am using patch request.
How is this usually done, using such data as an example? (Unfortunately, it did not work with pure Node.js and express). I haven’t dragged the database yet, I want to understand how to do it with the usual items array

//service 
 updateItem(id: string, updateItemDto: UpdateItemDto): Item
{

    const item = this.getItemById(id);

    const { name, lastname, prop1, prop2 } = updateItemDto;

    console.log(updateItemDto);

    return item;
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2021-01-12
@Isildur12

function filterObjectProps<O extends Record<string, unknown>, P extends keyof O>(obj: O, props: readonly P[]) {
  const entries: [P, O[P]][] = [];
  for(const prop of props) {
    if(prop in obj) {
      entries.push([prop, obj[prop]]);
    }
  }
  return Object.fromEntries(entries) as {
    [K in P]: O[K];
  };
}

// ...
updateItem(id: string, updateItemDto: UpdateItemDto): Item {
  const item = this.getItemById(id);
  return {
    ...item,
    ...filterObjectProps(updateItemDto, ['name', 'lastname', 'prop1', 'prop2'])
  };
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question