Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
6
Help us understand the problem. What is going on with this article?
@shinchit

[Node.js] オブジェクトから特定の key-value だけ抜き出したオブジェクトを作る

More than 3 years have passed since last update.

LodashpickBy 、または omitBy を使うと簡単です。

pickBy-and-omitBy-sample.js
let lodash = require('lodash');

let obj = {
    'pick_a': 'a',
    'pick_b': 'b',
    'omit_c': 'c',
    'omit_d': 'd'
};

/* obj から pick で始まる key だけからなるオブジェクト ( newObj ) を作成する */

let newObj;

// pickBy の例
newObj = lodash.pickBy(obj, function(value, key) {
    return key.match(/^pick_/);
});
// => { 'pick_a': 'a', 'pick_b': 'b' }

// omitBy の例
newObj = lodash.omitBy(obj, function(value, key) {
    return ! key.match(/^pick_/);
    // or return key.match(/^omit_/);
});
// => { 'pick_a': 'a', 'pick_b': 'b' }

pickBy は ピックアップするか否かの boolean を返す function を第二引数に、 omitBy は オミットするか否かの boolean を返す function を第二引数に渡します。

6
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
shinchit
「すべてはドキュメント( It's All Writing. )」を信条に働くソーシャルプログラマー。 plan text 大好き。コマンドライン大好き。vim 大好き。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
6
Help us understand the problem. What is going on with this article?