Destructure an object by an array of its keys









up vote
0
down vote

favorite












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"











share|improve this question



















  • 2




    No, because that would mean dynamic variable names, which are quite a code smell. (also, a is already defined)
    – CertainPerformance
    yesterday






  • 2




    I'm guessing you meant let arr_of_keys = ['a', 'd', 'e']? What you have is an array of references to some things.
    – Andy
    yesterday










  • @Andy Yeah, my bad, edited, thanks for the insight, completely missed it
    – Milan Velebit
    yesterday










  • Closest thing I found, stackoverflow.com/questions/17781472/…
    – Adi
    yesterday














up vote
0
down vote

favorite












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"











share|improve this question



















  • 2




    No, because that would mean dynamic variable names, which are quite a code smell. (also, a is already defined)
    – CertainPerformance
    yesterday






  • 2




    I'm guessing you meant let arr_of_keys = ['a', 'd', 'e']? What you have is an array of references to some things.
    – Andy
    yesterday










  • @Andy Yeah, my bad, edited, thanks for the insight, completely missed it
    – Milan Velebit
    yesterday










  • Closest thing I found, stackoverflow.com/questions/17781472/…
    – Adi
    yesterday












up vote
0
down vote

favorite









up vote
0
down vote

favorite











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"











share|improve this question















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"








javascript ecmascript-6






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited yesterday

























asked yesterday









Milan Velebit

6842619




6842619







  • 2




    No, because that would mean dynamic variable names, which are quite a code smell. (also, a is already defined)
    – CertainPerformance
    yesterday






  • 2




    I'm guessing you meant let arr_of_keys = ['a', 'd', 'e']? What you have is an array of references to some things.
    – Andy
    yesterday










  • @Andy Yeah, my bad, edited, thanks for the insight, completely missed it
    – Milan Velebit
    yesterday










  • Closest thing I found, stackoverflow.com/questions/17781472/…
    – Adi
    yesterday












  • 2




    No, because that would mean dynamic variable names, which are quite a code smell. (also, a is already defined)
    – CertainPerformance
    yesterday






  • 2




    I'm guessing you meant let arr_of_keys = ['a', 'd', 'e']? What you have is an array of references to some things.
    – Andy
    yesterday










  • @Andy Yeah, my bad, edited, thanks for the insight, completely missed it
    – Milan Velebit
    yesterday










  • Closest thing I found, stackoverflow.com/questions/17781472/…
    – Adi
    yesterday







2




2




No, because that would mean dynamic variable names, which are quite a code smell. (also, a is already defined)
– CertainPerformance
yesterday




No, because that would mean dynamic variable names, which are quite a code smell. (also, a is already defined)
– CertainPerformance
yesterday




2




2




I'm guessing you meant let arr_of_keys = ['a', 'd', 'e']? What you have is an array of references to some things.
– Andy
yesterday




I'm guessing you meant let arr_of_keys = ['a', 'd', 'e']? What you have is an array of references to some things.
– Andy
yesterday












@Andy Yeah, my bad, edited, thanks for the insight, completely missed it
– Milan Velebit
yesterday




@Andy Yeah, my bad, edited, thanks for the insight, completely missed it
– Milan Velebit
yesterday












Closest thing I found, stackoverflow.com/questions/17781472/…
– Adi
yesterday




Closest thing I found, stackoverflow.com/questions/17781472/…
– Adi
yesterday












2 Answers
2






active

oldest

votes

















up vote
2
down vote



accepted










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.)






share|improve this answer


















  • 1




    @dv reason for down-vote? The output matches the desired in OP.
    – Adriani6
    yesterday







  • 1




    it kinda doesn’t as it basically filters an object. OP said destructure which would create distinct variables.
    – evolutionxbox
    yesterday










  • @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.
    – Adriani6
    yesterday










  • 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
    yesterday

















up vote
1
down vote













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);








share|improve this answer




















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













     

    draft saved


    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53224413%2fdestructure-an-object-by-an-array-of-its-keys%23new-answer', 'question_page');

    );

    Post as a guest






























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    2
    down vote



    accepted










    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.)






    share|improve this answer


















    • 1




      @dv reason for down-vote? The output matches the desired in OP.
      – Adriani6
      yesterday







    • 1




      it kinda doesn’t as it basically filters an object. OP said destructure which would create distinct variables.
      – evolutionxbox
      yesterday










    • @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.
      – Adriani6
      yesterday










    • 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
      yesterday














    up vote
    2
    down vote



    accepted










    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.)






    share|improve this answer


















    • 1




      @dv reason for down-vote? The output matches the desired in OP.
      – Adriani6
      yesterday







    • 1




      it kinda doesn’t as it basically filters an object. OP said destructure which would create distinct variables.
      – evolutionxbox
      yesterday










    • @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.
      – Adriani6
      yesterday










    • 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
      yesterday












    up vote
    2
    down vote



    accepted







    up vote
    2
    down vote



    accepted






    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.)






    share|improve this answer














    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.)






    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)





    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)






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited yesterday

























    answered yesterday









    Adriani6

    3,8792923




    3,8792923







    • 1




      @dv reason for down-vote? The output matches the desired in OP.
      – Adriani6
      yesterday







    • 1




      it kinda doesn’t as it basically filters an object. OP said destructure which would create distinct variables.
      – evolutionxbox
      yesterday










    • @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.
      – Adriani6
      yesterday










    • 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
      yesterday












    • 1




      @dv reason for down-vote? The output matches the desired in OP.
      – Adriani6
      yesterday







    • 1




      it kinda doesn’t as it basically filters an object. OP said destructure which would create distinct variables.
      – evolutionxbox
      yesterday










    • @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.
      – Adriani6
      yesterday










    • 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
      yesterday







    1




    1




    @dv reason for down-vote? The output matches the desired in OP.
    – Adriani6
    yesterday





    @dv reason for down-vote? The output matches the desired in OP.
    – Adriani6
    yesterday





    1




    1




    it kinda doesn’t as it basically filters an object. OP said destructure which would create distinct variables.
    – evolutionxbox
    yesterday




    it kinda doesn’t as it basically filters an object. OP said destructure which would create distinct variables.
    – evolutionxbox
    yesterday












    @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.
    – Adriani6
    yesterday




    @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.
    – Adriani6
    yesterday












    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
    yesterday




    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
    yesterday












    up vote
    1
    down vote













    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);








    share|improve this answer
























      up vote
      1
      down vote













      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);








      share|improve this answer






















        up vote
        1
        down vote










        up vote
        1
        down vote









        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);








        share|improve this answer












        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);








        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);





        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);






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered yesterday









        Zsolt Gulyás

        337




        337



























             

            draft saved


            draft discarded















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53224413%2fdestructure-an-object-by-an-array-of-its-keys%23new-answer', 'question_page');

            );

            Post as a guest














































































            Popular posts from this blog

            How to how show current date and time by default on contact form 7 in WordPress without taking input from user in datetimepicker

            Syphilis

            Darth Vader #20