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

REPL で試してみたが、無理だった。

$ node
Welcome to Node.js v16.13.2.
Type ".help" for more information.
> const partial = {a,b,c} = {a:1,b:2,c:3,d:4}
undefined
> partial
{ a: 1, b: 2, c: 3, d: 4 }
> const partial = {...{a,b,c}} = {a:1,b:2,c:3,d:4}
const partial = {...{a,b,c}} = {a:1,b:2,c:3,d:4}
                    ^^^^^^^

Uncaught:
SyntaxError: `...` must be followed by an assignable reference in assignment contexts
> a
1
> b
2
> c
3
> d
Uncaught ReferenceError: d is not defined
>

@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