From 4c82dc854721f3f1b1006505e9229b3a00a2fdb9 Mon Sep 17 00:00:00 2001 From: yoshikazusawa <883514+yoshikazusawa@users.noreply.github.com> Date: Mon, 19 Feb 2024 23:16:21 +0900 Subject: [PATCH] Fix #393 remove a destructuring assignment example on _.pick native implementation --- README.md | 11 ++--------- tests/unit/all.js | 17 ++++++++--------- 2 files changed, 10 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index bfacc3f..1ba204f 100644 --- a/README.md +++ b/README.md @@ -2818,17 +2818,10 @@ Creates an object composed of the object properties predicate returns truthy for var object = { 'a': 1, 'b': '2', 'c': 3 }; // Underscore/Lodash - var result = _.pick(object, ['a', 'c']); + var result = _.pick(object, ['a', 'c', 'x']); console.log(result) // output: {a: 1, c: 3} - // Native - const { a, c } = object; - const result = { a, c}; - console.log(result); - // output: {a: 1, c: 3} - // for an array of this object --> array.map(({a, c}) => ({a, c})); - // Native function pick(object, keys) { return keys.reduce((obj, key) => { @@ -2838,7 +2831,7 @@ Creates an object composed of the object properties predicate returns truthy for return obj; }, {}); } - var result = pick(object, ['a', 'c']); + var result = pick(object, ['a', 'c', 'x']); console.log(result) // output: {a: 1, c: 3} ``` diff --git a/tests/unit/all.js b/tests/unit/all.js index 08d79fd..c7875d9 100644 --- a/tests/unit/all.js +++ b/tests/unit/all.js @@ -62,18 +62,17 @@ describe('code snippet example', () => { it('pick', () => { var object = { 'a': 1, 'b': '2', 'c': 3 }; - function pick(object, paths) { - const obj = {}; - for (const path of paths) { - if (object[path]) { - obj[path] = object[path] + function pick(object, keys) { + return keys.reduce((obj, key) => { + if (object && object.hasOwnProperty(key)) { + obj[key] = object[key]; } - } - return obj; + return obj; + }, {}); } assert.deepEqual( - _.pick(object, ['a', 'c']), - pick(object, ['a', 'c']) + _.pick(object, ['a', 'c', 'x']), + pick(object, ['a', 'c', 'x']) ) })