How to get a subset of a javascript object's properties
Using Object Destructuring and Property Shorthand
const object = { a: 5, b: 6, c: 7 };const picked = (({ a, c }) => ({ a, c }))(object);
console.log(picked); // { a: 5, c: 7 }
How to copy values of only a subset of object properties to another existing object in TypeScript
My suggestion for copyPropertyvalues()
would be something like this:
function copyPropertyvalues<T, K extends keyof T>(s: Pick<T, K>, d: T, ks: K[]) {
ks.forEach(k => d[k] = s[k]);
return d;
}
The function is generic in the type T
of the destination object, and the type K
of the key names you're going to copy from the source to the destination object. I assume that you want to require that the properties you're copying from the source should be the same type as the properties already in the destination; for example, you wouldn't copy the "a"
property from a source of type {a: number}
to a destination of type {a: string}
, since you'd be writing a number
to a string
and violating the type of the destination.
Note that we don't need the source object to be exactly T
; it only has to agree with T
at all the keys in K
. That is, we only say that it must be Pick<T, K>
using the Pick<T, K>
utility type.
And note that we are definitely passing in an array of key strings, which the compiler will infer not just as string
, but specifically as a union of string literal types which are a subset of keyof T
(using the keyof
type operator to get a union of the known keys of T
). So if you pass in ["b", "d"]
, the compiler will infer that as being of type Array<"b" | "d">
and not just Array<string>
. This will give you the type safety you're looking for, without trying to worry about something like nameof
which does not exist in JavaScript (and will not exist in TypeScript until it does, see microsoft/TypeScript#1579).
Okay, let's try it out:
copyPropertyvalues(
obj2, // source
obj1, // destination
["b", "d"] // properties to copy
);
console.log(obj1)
/* {
"a": "A",
"b": "B2",
"c": "C",
"d": "D2"
} */
Looks like it behaves how you want. And if you put the wrong keys in there you get compile time errors:
copyPropertyvalues(
obj2, // error!
obj1,
["a"]
)
copyPropertyvalues(
obj2,// error!
obj1,
["z"]
)
Playground link to code
Return object with subset of its attributes
Try this
function pick(data, keys) { var result = {}; keys.forEach(function (key) { if (data.hasOwnProperty(key)) { result[key] = data[key]; } }); return result;}
var data = { id: 3726492, kind: 'user', permalink: 'nicholas', username: 'Nicholas'}
var newData = pick(data, ['id', 'kind']);console.log(newData);
How to get a subset of a Javascript object with nested properties?
var docs = [{"id":"1","type":{"id":1,"desc":"Category 1"},"title":"Foo","date":"2018-06-21","attachments":[{"id":51,"filename":"foo.pdf","title":"Foo"},{"id":20,"filename":"bar.doc","title":"Bar"}]},{"id":"2","type":{"id":2,"desc":"Category 2"},"title":"Bar","date":"2018-06-21","attachments":[{"id":15,"filename":"foobar.xls","title":"Foobar"},{"id":201,"filename":"example.doc","title":"Example"}]}];
const result = docs.map(({id,type,attachments})=>{ let doc={id,type}; doc.attachments=attachments.map(({id})=>({id})); return doc;});
console.log(result);
Does Typescript support "subset types"?
Typescript now supports partial types.
The correct way to create a partial type is:
type PartialUser = Partial<IUser>;
Related Topics
Javascript Generate Unique Number Based on String
Replacing Multiple Elements of an Array While Keeping Their Position
Check If Token Expired Using This Jwt Library
Detect Click on HTML Button Through JavaScript in Android Webview
How to Highlight a Part of Text in Textarea
After Clicking a Button of Sweet Alert Call PHP File
How to Prevent Browser to Re-Set Inputs on Page Refresh
Chart.Js Showing Time (Hh:Mm:Ss - 24 Hour Clock) on Xaxis
Sequelize - How to Return Json Objects of the Database Results Only
Why Am I Getting Undefined as an Answer When Fetching Data from an API
Prevent Multiple Clicks .Click()
Angular 4 - Cannot Read Property Status of Null While Displaying Validation Error
Set Some Specific Options in Multiselect as Disabled and Selected
Angular 4:How to Get Index of Selected Value in a Datalist
404 Error When Trying to Register Serviceworker
Prevent Sweetalert to Be Closed on Clicking Outside the Popup Window