Skip to content

Instantly share code, notes, and snippets.

@takamin
Created February 17, 2022 03:10
Show Gist options
  • Save takamin/f66f17bf69dd6bec7abb79b8f8bdd2ed to your computer and use it in GitHub Desktop.
Save takamin/f66f17bf69dd6bec7abb79b8f8bdd2ed to your computer and use it in GitHub Desktop.
JavaScriptのオブジェクトから特定のキーだけを抜き出した別のオブジェクトを作る
/**
* 部分オブジェクトを取り出す。
* @param {string[]} keys 抜き出すキーの配列
* @param {Record<string, any>} obj 元のオブジェクト
* @returns {Record<string, any>} 指定されたキーのオブジェクトを返す(値は共有している)
*/
function getPartialObject(keys, obj) {
return (Object.entries(obj)
.filter(([key]) => keys.includes(key))
.reduce((obj, [key, value]) => {
obj[key] = value;
return obj;
}, {})
);
}
// サンプル
const obj = {
a: "A",
b: "B",
c: "C",
d: "D",
e: "E",
f: "F",
};
const keys = ["a","c","e","f"];
const partObj = getPartialObject(keys, obj);
console.log(`obj: ${JSON.stringify(obj, null, 2)}`);
console.log(`keys: ${JSON.stringify(keys)}`);
console.log(`partObj: ${JSON.stringify(partObj, null, 2)}`);
@takamin
Copy link
Author

takamin commented Feb 17, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment