0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

あるオブジェクトから特定のプロパティだけ取り出す « JavaScript

Last updated at Posted at 2017-09-30

色々勘違いしてた終わり。


lodash.pick(逆だけどlodash.omit)みたいなやつを使わずに。

// const obj = {a: 1, b: 2, c: 3};
Object.keys(obj)
  .reduce(
    (acc, key) => (
      ({}).hasOwnProperty.call(acc, key)
        ? {...acc, [key]: obj[key]}
        : acc
    ),
    {a: null, b: null}
  );

// => {a: 1, b: 2}

なんとなくdeepAssignな感じに改良。

// const obj = {a: {aa: 1, ab: 2}, b: {ba: 1, bb: 2}, c: {ca: 1, cb:2}};
Object.keys(obj)
  .reduce(
    (acc, key) => (
      ({}).hasOwnProperty.call(acc, key)
        ? {...acc, [key]: {...acc[key], ...obj[key]}}
        : {...acc, [key]: obj[key]}
    ),
    {a: {ac: 3}, b: {bc: 3}}
  );

// => {a: {aa: 1, ab: 2, ac: 3}, b: {ba: 1, bb: 2, bc: 3}, c: {ca: 1, cb:2}};
0
1
0

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?