I have this object:
{
"id": "Test",
"firstname": "Test",
"lastname": "Test",
"age": 83
}
but i want to return object only with this value:
{
"id": "Test"
}
how to cast first object to another one with using TS/NodeJS?
CodePudding user response:
You could write a function like this that uses a property accessor
to only return the id
of the object:
let data = { id: 'Test', firstname: 'Test', lastname: 'Test', age: 83, };
function trimToId(data) {
return { id: data.id };
}
console.log(trimToId(data))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
If you wanted to make this more concise you could use an arrow function
with destructuring
:
let data = { id: 'Test', firstname: 'Test', lastname: 'Test', age: 83 };
const trimToId = ({ id }) => ({ id });
console.log(trimToId(data));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
function foo(input) {
return {id: input.id};
}
CodePudding user response:
If your data is just as you presented it:
const object = {
id: "Test",
firstname: "Test",
lastname: "Test",
age: 83
}
const newObject = {id: object.id}
//or
const {id} = object;//destructuring
const newObject = {id};
CodePudding user response:
I think what you are looking for is a Utility Type called Partial. You can find the documentation here.
interface FirstObject {
id: string;
firstname: string;
lastname: string;
age: number;
}
const firstObject: FirstObject = {
"id": "Test",
"firstname": "Test",
"lastname": "Test",
"age": 83
};
const secondObject: Partial<FirstObject> = {
"_id": "Test"
};
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>