1

Say that we have an object like this one:

let obj = {a: "John", b: "Sarah", c: "Lara", d: "Joseph", e: "Roger"}

And an array of some of its keys:

let arr_of_keys = ["a", "d", "e"]

Is it possible to destructure the object using the predefined keys in the array, something along the lines of:

let {...arr_of_keys} = obj;

To finally end up with:

a = "John", d = "Joseph", e = "Roger"

Milan Velebit
  • 1,933
  • 2
  • 15
  • 32

2 Answers2

1

You want a simple .reduce method like the one below:

var result = arr_of_keys.reduce(function(o,item){

    if(obj.hasOwnProperty(item)){
        o[item] = obj[item]; 
    }

  return o;
}, {});

Here's an example:

let obj = {a: "John", b: "Sarah", c: "Lara", d: "Joseph", e: "Roger"}
let arr_of_keys = ["a", "d", "e", "f"];

var result = arr_of_keys.reduce(function(o,item){

 if(obj.hasOwnProperty(item)){
   o[item] = obj[item]; 
  }
  
  return o;
}, {});

console.log(result)

Here's a JSFiddle runnable (since the built-in one returns a 503.)

Adrian
  • 8,271
  • 2
  • 26
  • 43
  • 1
    it kinda doesn’t as it basically filters an object. OP said destructure which would create distinct variables. – evolutionxbox Nov 09 '18 at 13:10
  • @evolutionxbox "It kinda doesn't" isn't a valid reason. Just because the wording of a question states something it doesn't mean it's the way to go. Also you need to filter an object given you have two arrays to work with where values in one depend on the outcome - so at some point, a filter will take place regardless. In my answer there is no need for deconstructing an object. – Adrian Nov 09 '18 at 14:12
  • I'm aware. I used the word "kinda" for that reason. I should have stated that I agree with your reasoning and the solution provided is better than what the OP was asking for. – evolutionxbox Nov 09 '18 at 15:05
1

Here is a possible helper function for the provided issue. I added a set conversion to remove possible duplications in order save resources. Also added simple error handling in form of console error messages.

const obj = {a: "John", b: "Sarah", c: "Lara", d: "Joseph", e: "Roger"}

const arr_of_keys = ["a", "d", "e"];


const customObjectDescructurer = (arrayOfDesiredPropKeys, object) => {

  const setOfDesiredPropKeys = new Set(arrayOfDesiredPropKeys);
  
  const filteredObject = [...setOfDesiredPropKeys].reduce(
    (filteredObject, desiredPropKey) => {
      if(object.hasOwnProperty(desiredPropKey)){
        filteredObject[desiredPropKey] = object[desiredPropKey];
      } else {
        console.error(`
          The given ${desiredPropKey}, does not exist in ${object} object.
        `);
      }
      return filteredObject;
    }, {});

  return filteredObject;
  
}


const desiredKeys = customObjectDescructurer(arr_of_keys, obj);

console.log(desiredKeys);
webpreneur
  • 795
  • 9
  • 15