LoginSignup
3
0

More than 1 year has passed since last update.

オブジェクトリストから削除リストにある項目以外を抽出する(非破壊)

Last updated at Posted at 2022-03-14

teratailの質問に回答したコードを、Qiitaにも残しておきます。

元データを変更せず(非破壊)に、除外リストで指定された項目を取り除いたオブジェクトリストを新たに作る方法です。

  1. オブジェクトリストをmapして別のオブジェクトリストを作る
  2. 各オブジェクトからObject.entries[key, value]リストを列挙する
  3. 削除しない項目をfilterで抽出する
  4. Object.fromEntries でオブジェクトにする
const members = [
    { firstname: 'Taro', lastname: 'Yamada', age: 20 },
    { firstname: 'Hanako', lastname: 'Hanako', age: 10 },
];

const secrets = [ 'lastname', 'age' ];

const anonymous = members.map(member =>
    Object.fromEntries(Object.entries(member)
                             .filter(([key, value]) => !secrets.includes(key))))
console.log(anonymous)
実行結果
[ { firstname: 'Taro' }, { firstname: 'Hanako' } ]
3
0
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0