Created
February 17, 2022 03:10
-
-
Save takamin/f66f17bf69dd6bec7abb79b8f8bdd2ed to your computer and use it in GitHub Desktop.
JavaScriptのオブジェクトから特定のキーだけを抜き出した別のオブジェクトを作る
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 部分オブジェクトを取り出す。 | |
* @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)}`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
REPL で試してみたが、無理だった。