Javascript converting 2 string arrays to map











up vote
-2
down vote

favorite












I have two string arrays keys and values:






let keys = [a,b,c,d]
let values = [1,2,3,4]





How to convert them into a map?



Expected output would be:



{a: "1", b: "2", c: "3", d: "4"}









share|improve this question
























  • Similar question made for Java: stackoverflow.com/questions/12418334/…
    – Pranay
    Nov 9 at 16:29










  • @Pranay how you want the output?
    – Code-EZ
    Nov 9 at 16:31










  • You can start by writing some code.
    – slider
    Nov 9 at 16:32






  • 3




    What code have you tried already? What is your expected output? Do you want an actual JavaScript Map or just a plain object? (Since those have keys/values as well).
    – Herohtar
    Nov 9 at 16:33










  • Expected output would be: {a: "1", b: "2", c: "3", d: "4"}
    – Pranay
    Nov 9 at 16:35















up vote
-2
down vote

favorite












I have two string arrays keys and values:






let keys = [a,b,c,d]
let values = [1,2,3,4]





How to convert them into a map?



Expected output would be:



{a: "1", b: "2", c: "3", d: "4"}









share|improve this question
























  • Similar question made for Java: stackoverflow.com/questions/12418334/…
    – Pranay
    Nov 9 at 16:29










  • @Pranay how you want the output?
    – Code-EZ
    Nov 9 at 16:31










  • You can start by writing some code.
    – slider
    Nov 9 at 16:32






  • 3




    What code have you tried already? What is your expected output? Do you want an actual JavaScript Map or just a plain object? (Since those have keys/values as well).
    – Herohtar
    Nov 9 at 16:33










  • Expected output would be: {a: "1", b: "2", c: "3", d: "4"}
    – Pranay
    Nov 9 at 16:35













up vote
-2
down vote

favorite









up vote
-2
down vote

favorite











I have two string arrays keys and values:






let keys = [a,b,c,d]
let values = [1,2,3,4]





How to convert them into a map?



Expected output would be:



{a: "1", b: "2", c: "3", d: "4"}









share|improve this question















I have two string arrays keys and values:






let keys = [a,b,c,d]
let values = [1,2,3,4]





How to convert them into a map?



Expected output would be:



{a: "1", b: "2", c: "3", d: "4"}





let keys = [a,b,c,d]
let values = [1,2,3,4]





let keys = [a,b,c,d]
let values = [1,2,3,4]






javascript






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 9 at 16:35









Paul Fitzgerald

5,1821633




5,1821633










asked Nov 9 at 16:28









Pranay

4510




4510












  • Similar question made for Java: stackoverflow.com/questions/12418334/…
    – Pranay
    Nov 9 at 16:29










  • @Pranay how you want the output?
    – Code-EZ
    Nov 9 at 16:31










  • You can start by writing some code.
    – slider
    Nov 9 at 16:32






  • 3




    What code have you tried already? What is your expected output? Do you want an actual JavaScript Map or just a plain object? (Since those have keys/values as well).
    – Herohtar
    Nov 9 at 16:33










  • Expected output would be: {a: "1", b: "2", c: "3", d: "4"}
    – Pranay
    Nov 9 at 16:35


















  • Similar question made for Java: stackoverflow.com/questions/12418334/…
    – Pranay
    Nov 9 at 16:29










  • @Pranay how you want the output?
    – Code-EZ
    Nov 9 at 16:31










  • You can start by writing some code.
    – slider
    Nov 9 at 16:32






  • 3




    What code have you tried already? What is your expected output? Do you want an actual JavaScript Map or just a plain object? (Since those have keys/values as well).
    – Herohtar
    Nov 9 at 16:33










  • Expected output would be: {a: "1", b: "2", c: "3", d: "4"}
    – Pranay
    Nov 9 at 16:35
















Similar question made for Java: stackoverflow.com/questions/12418334/…
– Pranay
Nov 9 at 16:29




Similar question made for Java: stackoverflow.com/questions/12418334/…
– Pranay
Nov 9 at 16:29












@Pranay how you want the output?
– Code-EZ
Nov 9 at 16:31




@Pranay how you want the output?
– Code-EZ
Nov 9 at 16:31












You can start by writing some code.
– slider
Nov 9 at 16:32




You can start by writing some code.
– slider
Nov 9 at 16:32




3




3




What code have you tried already? What is your expected output? Do you want an actual JavaScript Map or just a plain object? (Since those have keys/values as well).
– Herohtar
Nov 9 at 16:33




What code have you tried already? What is your expected output? Do you want an actual JavaScript Map or just a plain object? (Since those have keys/values as well).
– Herohtar
Nov 9 at 16:33












Expected output would be: {a: "1", b: "2", c: "3", d: "4"}
– Pranay
Nov 9 at 16:35




Expected output would be: {a: "1", b: "2", c: "3", d: "4"}
– Pranay
Nov 9 at 16:35












6 Answers
6






active

oldest

votes

















up vote
8
down vote



accepted










you can use Map in ES6



var myMap = new Map();

// setting the values
myMap.set('key1', 'value1');
myMap.set('key2', 'value2');
myMap.set('key3', 'value3');


your answer :



for (let i = 0; i < keys.length; i++) {
myMap.set(keys[i], values[i]);
}





share|improve this answer



















  • 1




    Come on, what is the point of downvoting an answer if you do not agree with the question?
    – Loredra L
    Nov 9 at 16:33






  • 1




    Why downvote that good answer
    – InitialCrow
    Nov 9 at 16:34






  • 3




    @LoredraL It wasn't a good answer and it wasn't about not agreeing with the question. It was that the first attempt wasn't complete - it didn't generate the needed output based on the given inputs.
    – Adriani6
    Nov 9 at 16:43












  • Thanks for the answer!
    – Pranay
    Nov 9 at 16:44


















up vote
3
down vote













Firstly create an object. Then loop through your array and add the keys and values to the object.






let keys = ['a','b','c','d'];
let values = [1,2,3,4];

let obj = {};

keys.forEach((key, index) => {
obj[key] = values[index]
});

console.log(obj);








share|improve this answer





















  • IMO map would be a better fit than forEach.
    – evolutionxbox
    Nov 9 at 16:36












  • Why do you think that? :-)
    – Paul Fitzgerald
    Nov 9 at 16:36










  • Actually, I don't... changed my mind after thinking about it for a moment.
    – evolutionxbox
    Nov 9 at 16:37








  • 1




    haha, fair enough! :-D
    – Paul Fitzgerald
    Nov 9 at 16:38








  • 2




    Thanks for the answer!
    – Pranay
    Nov 9 at 16:45


















up vote
1
down vote













You can use array reduce on any of the array and use index to retrieve value from another array






let keys = ['a', 'b', 'c', 'd'];
let values = [1, 2, 3, 4];
let k = keys.reduce((acc, curr, index) => {
acc[curr] = values[index]
return acc;
}, {});

console.log(k)








share|improve this answer




























    up vote
    1
    down vote













    First of all, you need to declare your string arrays properly.






    let keys = ['a', 'b', 'c', 'd'];
    let values = ['1', '2', '3', '4'];

    var zip = (target, ...arr) => {
    if (target == null) throw Error('Target is undefined');
    if (arr[0] == null || arr[1] == null) throw Error('Lists must not be null');
    if (arr[0].length !== arr[1].length) throw Error('Lists must match in length');
    if (Array.isArray(target)) {
    arr[0].forEach((x, i) => target.push([arr[0][i], arr[1][i]]));
    } else if (typeof target === 'object') {
    arr[0].forEach((x, i) => target[arr[0][i]] = arr[1][i]);
    } else {
    throw Error('Unsupported target type');
    }
    return target;
    }

    var zipObj = (...arr) => zip.call(null, {}, ...arr);
    var zipArr = (...arr) => zip.call(null, , ...arr);

    //console.log(zip({}, keys, values));
    console.log(zipObj(keys, values)); // Zip object

    //console.log(zip(, keys, values));
    console.log(zipArr(keys, values)); // Zip array

    .as-console-wrapper { top: 0; max-height: 100% !important; }








    share|improve this answer























    • Thanks for the answer!
      – Pranay
      Nov 9 at 16:45


















    up vote
    0
    down vote













    When using lodash this is a one-liner:



    _.zipObject(keys,values)





    share|improve this answer




























      up vote
      0
      down vote













      This should do the trick:



      let keys = ['a','b','c','d']
      let values = [1,2,3,4]
      let mapped = keys.reduce((accumulator, current, index) => {
      accumulator[current] = values[index];
      return accumulator;
      }, {});

      console.log(mapped)
      // Result should be:
      {a: 1, b: 2, c: 3, d: 4}


      Reduce is a powerful method that can be used for all sorts of tasks.



      Here we're "reducing" the given values of keys into an object where keys are the key and values are the correlating values.



      The first parameter in reduce is a callback function that you need to pass along at minimum accumulator and current variables (can have different names); the other parameters are index and array which represent the current index of the iteration and the original array that is being iterated.



      The second parameter is the initial value of the accumulator; by default it will be the first current value but in our case we set it to {} so we can treat it as an object.



      I hope this helps!






      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%2f53229659%2fjavascript-converting-2-string-arrays-to-map%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        6 Answers
        6






        active

        oldest

        votes








        6 Answers
        6






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes








        up vote
        8
        down vote



        accepted










        you can use Map in ES6



        var myMap = new Map();

        // setting the values
        myMap.set('key1', 'value1');
        myMap.set('key2', 'value2');
        myMap.set('key3', 'value3');


        your answer :



        for (let i = 0; i < keys.length; i++) {
        myMap.set(keys[i], values[i]);
        }





        share|improve this answer



















        • 1




          Come on, what is the point of downvoting an answer if you do not agree with the question?
          – Loredra L
          Nov 9 at 16:33






        • 1




          Why downvote that good answer
          – InitialCrow
          Nov 9 at 16:34






        • 3




          @LoredraL It wasn't a good answer and it wasn't about not agreeing with the question. It was that the first attempt wasn't complete - it didn't generate the needed output based on the given inputs.
          – Adriani6
          Nov 9 at 16:43












        • Thanks for the answer!
          – Pranay
          Nov 9 at 16:44















        up vote
        8
        down vote



        accepted










        you can use Map in ES6



        var myMap = new Map();

        // setting the values
        myMap.set('key1', 'value1');
        myMap.set('key2', 'value2');
        myMap.set('key3', 'value3');


        your answer :



        for (let i = 0; i < keys.length; i++) {
        myMap.set(keys[i], values[i]);
        }





        share|improve this answer



















        • 1




          Come on, what is the point of downvoting an answer if you do not agree with the question?
          – Loredra L
          Nov 9 at 16:33






        • 1




          Why downvote that good answer
          – InitialCrow
          Nov 9 at 16:34






        • 3




          @LoredraL It wasn't a good answer and it wasn't about not agreeing with the question. It was that the first attempt wasn't complete - it didn't generate the needed output based on the given inputs.
          – Adriani6
          Nov 9 at 16:43












        • Thanks for the answer!
          – Pranay
          Nov 9 at 16:44













        up vote
        8
        down vote



        accepted







        up vote
        8
        down vote



        accepted






        you can use Map in ES6



        var myMap = new Map();

        // setting the values
        myMap.set('key1', 'value1');
        myMap.set('key2', 'value2');
        myMap.set('key3', 'value3');


        your answer :



        for (let i = 0; i < keys.length; i++) {
        myMap.set(keys[i], values[i]);
        }





        share|improve this answer














        you can use Map in ES6



        var myMap = new Map();

        // setting the values
        myMap.set('key1', 'value1');
        myMap.set('key2', 'value2');
        myMap.set('key3', 'value3');


        your answer :



        for (let i = 0; i < keys.length; i++) {
        myMap.set(keys[i], values[i]);
        }






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 9 at 16:37

























        answered Nov 9 at 16:31









        Yashar Panahi

        932816




        932816








        • 1




          Come on, what is the point of downvoting an answer if you do not agree with the question?
          – Loredra L
          Nov 9 at 16:33






        • 1




          Why downvote that good answer
          – InitialCrow
          Nov 9 at 16:34






        • 3




          @LoredraL It wasn't a good answer and it wasn't about not agreeing with the question. It was that the first attempt wasn't complete - it didn't generate the needed output based on the given inputs.
          – Adriani6
          Nov 9 at 16:43












        • Thanks for the answer!
          – Pranay
          Nov 9 at 16:44














        • 1




          Come on, what is the point of downvoting an answer if you do not agree with the question?
          – Loredra L
          Nov 9 at 16:33






        • 1




          Why downvote that good answer
          – InitialCrow
          Nov 9 at 16:34






        • 3




          @LoredraL It wasn't a good answer and it wasn't about not agreeing with the question. It was that the first attempt wasn't complete - it didn't generate the needed output based on the given inputs.
          – Adriani6
          Nov 9 at 16:43












        • Thanks for the answer!
          – Pranay
          Nov 9 at 16:44








        1




        1




        Come on, what is the point of downvoting an answer if you do not agree with the question?
        – Loredra L
        Nov 9 at 16:33




        Come on, what is the point of downvoting an answer if you do not agree with the question?
        – Loredra L
        Nov 9 at 16:33




        1




        1




        Why downvote that good answer
        – InitialCrow
        Nov 9 at 16:34




        Why downvote that good answer
        – InitialCrow
        Nov 9 at 16:34




        3




        3




        @LoredraL It wasn't a good answer and it wasn't about not agreeing with the question. It was that the first attempt wasn't complete - it didn't generate the needed output based on the given inputs.
        – Adriani6
        Nov 9 at 16:43






        @LoredraL It wasn't a good answer and it wasn't about not agreeing with the question. It was that the first attempt wasn't complete - it didn't generate the needed output based on the given inputs.
        – Adriani6
        Nov 9 at 16:43














        Thanks for the answer!
        – Pranay
        Nov 9 at 16:44




        Thanks for the answer!
        – Pranay
        Nov 9 at 16:44












        up vote
        3
        down vote













        Firstly create an object. Then loop through your array and add the keys and values to the object.






        let keys = ['a','b','c','d'];
        let values = [1,2,3,4];

        let obj = {};

        keys.forEach((key, index) => {
        obj[key] = values[index]
        });

        console.log(obj);








        share|improve this answer





















        • IMO map would be a better fit than forEach.
          – evolutionxbox
          Nov 9 at 16:36












        • Why do you think that? :-)
          – Paul Fitzgerald
          Nov 9 at 16:36










        • Actually, I don't... changed my mind after thinking about it for a moment.
          – evolutionxbox
          Nov 9 at 16:37








        • 1




          haha, fair enough! :-D
          – Paul Fitzgerald
          Nov 9 at 16:38








        • 2




          Thanks for the answer!
          – Pranay
          Nov 9 at 16:45















        up vote
        3
        down vote













        Firstly create an object. Then loop through your array and add the keys and values to the object.






        let keys = ['a','b','c','d'];
        let values = [1,2,3,4];

        let obj = {};

        keys.forEach((key, index) => {
        obj[key] = values[index]
        });

        console.log(obj);








        share|improve this answer





















        • IMO map would be a better fit than forEach.
          – evolutionxbox
          Nov 9 at 16:36












        • Why do you think that? :-)
          – Paul Fitzgerald
          Nov 9 at 16:36










        • Actually, I don't... changed my mind after thinking about it for a moment.
          – evolutionxbox
          Nov 9 at 16:37








        • 1




          haha, fair enough! :-D
          – Paul Fitzgerald
          Nov 9 at 16:38








        • 2




          Thanks for the answer!
          – Pranay
          Nov 9 at 16:45













        up vote
        3
        down vote










        up vote
        3
        down vote









        Firstly create an object. Then loop through your array and add the keys and values to the object.






        let keys = ['a','b','c','d'];
        let values = [1,2,3,4];

        let obj = {};

        keys.forEach((key, index) => {
        obj[key] = values[index]
        });

        console.log(obj);








        share|improve this answer












        Firstly create an object. Then loop through your array and add the keys and values to the object.






        let keys = ['a','b','c','d'];
        let values = [1,2,3,4];

        let obj = {};

        keys.forEach((key, index) => {
        obj[key] = values[index]
        });

        console.log(obj);








        let keys = ['a','b','c','d'];
        let values = [1,2,3,4];

        let obj = {};

        keys.forEach((key, index) => {
        obj[key] = values[index]
        });

        console.log(obj);





        let keys = ['a','b','c','d'];
        let values = [1,2,3,4];

        let obj = {};

        keys.forEach((key, index) => {
        obj[key] = values[index]
        });

        console.log(obj);






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 9 at 16:33









        Paul Fitzgerald

        5,1821633




        5,1821633












        • IMO map would be a better fit than forEach.
          – evolutionxbox
          Nov 9 at 16:36












        • Why do you think that? :-)
          – Paul Fitzgerald
          Nov 9 at 16:36










        • Actually, I don't... changed my mind after thinking about it for a moment.
          – evolutionxbox
          Nov 9 at 16:37








        • 1




          haha, fair enough! :-D
          – Paul Fitzgerald
          Nov 9 at 16:38








        • 2




          Thanks for the answer!
          – Pranay
          Nov 9 at 16:45


















        • IMO map would be a better fit than forEach.
          – evolutionxbox
          Nov 9 at 16:36












        • Why do you think that? :-)
          – Paul Fitzgerald
          Nov 9 at 16:36










        • Actually, I don't... changed my mind after thinking about it for a moment.
          – evolutionxbox
          Nov 9 at 16:37








        • 1




          haha, fair enough! :-D
          – Paul Fitzgerald
          Nov 9 at 16:38








        • 2




          Thanks for the answer!
          – Pranay
          Nov 9 at 16:45
















        IMO map would be a better fit than forEach.
        – evolutionxbox
        Nov 9 at 16:36






        IMO map would be a better fit than forEach.
        – evolutionxbox
        Nov 9 at 16:36














        Why do you think that? :-)
        – Paul Fitzgerald
        Nov 9 at 16:36




        Why do you think that? :-)
        – Paul Fitzgerald
        Nov 9 at 16:36












        Actually, I don't... changed my mind after thinking about it for a moment.
        – evolutionxbox
        Nov 9 at 16:37






        Actually, I don't... changed my mind after thinking about it for a moment.
        – evolutionxbox
        Nov 9 at 16:37






        1




        1




        haha, fair enough! :-D
        – Paul Fitzgerald
        Nov 9 at 16:38






        haha, fair enough! :-D
        – Paul Fitzgerald
        Nov 9 at 16:38






        2




        2




        Thanks for the answer!
        – Pranay
        Nov 9 at 16:45




        Thanks for the answer!
        – Pranay
        Nov 9 at 16:45










        up vote
        1
        down vote













        You can use array reduce on any of the array and use index to retrieve value from another array






        let keys = ['a', 'b', 'c', 'd'];
        let values = [1, 2, 3, 4];
        let k = keys.reduce((acc, curr, index) => {
        acc[curr] = values[index]
        return acc;
        }, {});

        console.log(k)








        share|improve this answer

























          up vote
          1
          down vote













          You can use array reduce on any of the array and use index to retrieve value from another array






          let keys = ['a', 'b', 'c', 'd'];
          let values = [1, 2, 3, 4];
          let k = keys.reduce((acc, curr, index) => {
          acc[curr] = values[index]
          return acc;
          }, {});

          console.log(k)








          share|improve this answer























            up vote
            1
            down vote










            up vote
            1
            down vote









            You can use array reduce on any of the array and use index to retrieve value from another array






            let keys = ['a', 'b', 'c', 'd'];
            let values = [1, 2, 3, 4];
            let k = keys.reduce((acc, curr, index) => {
            acc[curr] = values[index]
            return acc;
            }, {});

            console.log(k)








            share|improve this answer












            You can use array reduce on any of the array and use index to retrieve value from another array






            let keys = ['a', 'b', 'c', 'd'];
            let values = [1, 2, 3, 4];
            let k = keys.reduce((acc, curr, index) => {
            acc[curr] = values[index]
            return acc;
            }, {});

            console.log(k)








            let keys = ['a', 'b', 'c', 'd'];
            let values = [1, 2, 3, 4];
            let k = keys.reduce((acc, curr, index) => {
            acc[curr] = values[index]
            return acc;
            }, {});

            console.log(k)





            let keys = ['a', 'b', 'c', 'd'];
            let values = [1, 2, 3, 4];
            let k = keys.reduce((acc, curr, index) => {
            acc[curr] = values[index]
            return acc;
            }, {});

            console.log(k)






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 9 at 16:37









            brk

            24.9k31939




            24.9k31939






















                up vote
                1
                down vote













                First of all, you need to declare your string arrays properly.






                let keys = ['a', 'b', 'c', 'd'];
                let values = ['1', '2', '3', '4'];

                var zip = (target, ...arr) => {
                if (target == null) throw Error('Target is undefined');
                if (arr[0] == null || arr[1] == null) throw Error('Lists must not be null');
                if (arr[0].length !== arr[1].length) throw Error('Lists must match in length');
                if (Array.isArray(target)) {
                arr[0].forEach((x, i) => target.push([arr[0][i], arr[1][i]]));
                } else if (typeof target === 'object') {
                arr[0].forEach((x, i) => target[arr[0][i]] = arr[1][i]);
                } else {
                throw Error('Unsupported target type');
                }
                return target;
                }

                var zipObj = (...arr) => zip.call(null, {}, ...arr);
                var zipArr = (...arr) => zip.call(null, , ...arr);

                //console.log(zip({}, keys, values));
                console.log(zipObj(keys, values)); // Zip object

                //console.log(zip(, keys, values));
                console.log(zipArr(keys, values)); // Zip array

                .as-console-wrapper { top: 0; max-height: 100% !important; }








                share|improve this answer























                • Thanks for the answer!
                  – Pranay
                  Nov 9 at 16:45















                up vote
                1
                down vote













                First of all, you need to declare your string arrays properly.






                let keys = ['a', 'b', 'c', 'd'];
                let values = ['1', '2', '3', '4'];

                var zip = (target, ...arr) => {
                if (target == null) throw Error('Target is undefined');
                if (arr[0] == null || arr[1] == null) throw Error('Lists must not be null');
                if (arr[0].length !== arr[1].length) throw Error('Lists must match in length');
                if (Array.isArray(target)) {
                arr[0].forEach((x, i) => target.push([arr[0][i], arr[1][i]]));
                } else if (typeof target === 'object') {
                arr[0].forEach((x, i) => target[arr[0][i]] = arr[1][i]);
                } else {
                throw Error('Unsupported target type');
                }
                return target;
                }

                var zipObj = (...arr) => zip.call(null, {}, ...arr);
                var zipArr = (...arr) => zip.call(null, , ...arr);

                //console.log(zip({}, keys, values));
                console.log(zipObj(keys, values)); // Zip object

                //console.log(zip(, keys, values));
                console.log(zipArr(keys, values)); // Zip array

                .as-console-wrapper { top: 0; max-height: 100% !important; }








                share|improve this answer























                • Thanks for the answer!
                  – Pranay
                  Nov 9 at 16:45













                up vote
                1
                down vote










                up vote
                1
                down vote









                First of all, you need to declare your string arrays properly.






                let keys = ['a', 'b', 'c', 'd'];
                let values = ['1', '2', '3', '4'];

                var zip = (target, ...arr) => {
                if (target == null) throw Error('Target is undefined');
                if (arr[0] == null || arr[1] == null) throw Error('Lists must not be null');
                if (arr[0].length !== arr[1].length) throw Error('Lists must match in length');
                if (Array.isArray(target)) {
                arr[0].forEach((x, i) => target.push([arr[0][i], arr[1][i]]));
                } else if (typeof target === 'object') {
                arr[0].forEach((x, i) => target[arr[0][i]] = arr[1][i]);
                } else {
                throw Error('Unsupported target type');
                }
                return target;
                }

                var zipObj = (...arr) => zip.call(null, {}, ...arr);
                var zipArr = (...arr) => zip.call(null, , ...arr);

                //console.log(zip({}, keys, values));
                console.log(zipObj(keys, values)); // Zip object

                //console.log(zip(, keys, values));
                console.log(zipArr(keys, values)); // Zip array

                .as-console-wrapper { top: 0; max-height: 100% !important; }








                share|improve this answer














                First of all, you need to declare your string arrays properly.






                let keys = ['a', 'b', 'c', 'd'];
                let values = ['1', '2', '3', '4'];

                var zip = (target, ...arr) => {
                if (target == null) throw Error('Target is undefined');
                if (arr[0] == null || arr[1] == null) throw Error('Lists must not be null');
                if (arr[0].length !== arr[1].length) throw Error('Lists must match in length');
                if (Array.isArray(target)) {
                arr[0].forEach((x, i) => target.push([arr[0][i], arr[1][i]]));
                } else if (typeof target === 'object') {
                arr[0].forEach((x, i) => target[arr[0][i]] = arr[1][i]);
                } else {
                throw Error('Unsupported target type');
                }
                return target;
                }

                var zipObj = (...arr) => zip.call(null, {}, ...arr);
                var zipArr = (...arr) => zip.call(null, , ...arr);

                //console.log(zip({}, keys, values));
                console.log(zipObj(keys, values)); // Zip object

                //console.log(zip(, keys, values));
                console.log(zipArr(keys, values)); // Zip array

                .as-console-wrapper { top: 0; max-height: 100% !important; }








                let keys = ['a', 'b', 'c', 'd'];
                let values = ['1', '2', '3', '4'];

                var zip = (target, ...arr) => {
                if (target == null) throw Error('Target is undefined');
                if (arr[0] == null || arr[1] == null) throw Error('Lists must not be null');
                if (arr[0].length !== arr[1].length) throw Error('Lists must match in length');
                if (Array.isArray(target)) {
                arr[0].forEach((x, i) => target.push([arr[0][i], arr[1][i]]));
                } else if (typeof target === 'object') {
                arr[0].forEach((x, i) => target[arr[0][i]] = arr[1][i]);
                } else {
                throw Error('Unsupported target type');
                }
                return target;
                }

                var zipObj = (...arr) => zip.call(null, {}, ...arr);
                var zipArr = (...arr) => zip.call(null, , ...arr);

                //console.log(zip({}, keys, values));
                console.log(zipObj(keys, values)); // Zip object

                //console.log(zip(, keys, values));
                console.log(zipArr(keys, values)); // Zip array

                .as-console-wrapper { top: 0; max-height: 100% !important; }





                let keys = ['a', 'b', 'c', 'd'];
                let values = ['1', '2', '3', '4'];

                var zip = (target, ...arr) => {
                if (target == null) throw Error('Target is undefined');
                if (arr[0] == null || arr[1] == null) throw Error('Lists must not be null');
                if (arr[0].length !== arr[1].length) throw Error('Lists must match in length');
                if (Array.isArray(target)) {
                arr[0].forEach((x, i) => target.push([arr[0][i], arr[1][i]]));
                } else if (typeof target === 'object') {
                arr[0].forEach((x, i) => target[arr[0][i]] = arr[1][i]);
                } else {
                throw Error('Unsupported target type');
                }
                return target;
                }

                var zipObj = (...arr) => zip.call(null, {}, ...arr);
                var zipArr = (...arr) => zip.call(null, , ...arr);

                //console.log(zip({}, keys, values));
                console.log(zipObj(keys, values)); // Zip object

                //console.log(zip(, keys, values));
                console.log(zipArr(keys, values)); // Zip array

                .as-console-wrapper { top: 0; max-height: 100% !important; }






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 9 at 16:53

























                answered Nov 9 at 16:41









                Mr. Polywhirl

                16.2k84783




                16.2k84783












                • Thanks for the answer!
                  – Pranay
                  Nov 9 at 16:45


















                • Thanks for the answer!
                  – Pranay
                  Nov 9 at 16:45
















                Thanks for the answer!
                – Pranay
                Nov 9 at 16:45




                Thanks for the answer!
                – Pranay
                Nov 9 at 16:45










                up vote
                0
                down vote













                When using lodash this is a one-liner:



                _.zipObject(keys,values)





                share|improve this answer

























                  up vote
                  0
                  down vote













                  When using lodash this is a one-liner:



                  _.zipObject(keys,values)





                  share|improve this answer























                    up vote
                    0
                    down vote










                    up vote
                    0
                    down vote









                    When using lodash this is a one-liner:



                    _.zipObject(keys,values)





                    share|improve this answer












                    When using lodash this is a one-liner:



                    _.zipObject(keys,values)






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 9 at 16:41









                    Dr Hund

                    5681711




                    5681711






















                        up vote
                        0
                        down vote













                        This should do the trick:



                        let keys = ['a','b','c','d']
                        let values = [1,2,3,4]
                        let mapped = keys.reduce((accumulator, current, index) => {
                        accumulator[current] = values[index];
                        return accumulator;
                        }, {});

                        console.log(mapped)
                        // Result should be:
                        {a: 1, b: 2, c: 3, d: 4}


                        Reduce is a powerful method that can be used for all sorts of tasks.



                        Here we're "reducing" the given values of keys into an object where keys are the key and values are the correlating values.



                        The first parameter in reduce is a callback function that you need to pass along at minimum accumulator and current variables (can have different names); the other parameters are index and array which represent the current index of the iteration and the original array that is being iterated.



                        The second parameter is the initial value of the accumulator; by default it will be the first current value but in our case we set it to {} so we can treat it as an object.



                        I hope this helps!






                        share|improve this answer

























                          up vote
                          0
                          down vote













                          This should do the trick:



                          let keys = ['a','b','c','d']
                          let values = [1,2,3,4]
                          let mapped = keys.reduce((accumulator, current, index) => {
                          accumulator[current] = values[index];
                          return accumulator;
                          }, {});

                          console.log(mapped)
                          // Result should be:
                          {a: 1, b: 2, c: 3, d: 4}


                          Reduce is a powerful method that can be used for all sorts of tasks.



                          Here we're "reducing" the given values of keys into an object where keys are the key and values are the correlating values.



                          The first parameter in reduce is a callback function that you need to pass along at minimum accumulator and current variables (can have different names); the other parameters are index and array which represent the current index of the iteration and the original array that is being iterated.



                          The second parameter is the initial value of the accumulator; by default it will be the first current value but in our case we set it to {} so we can treat it as an object.



                          I hope this helps!






                          share|improve this answer























                            up vote
                            0
                            down vote










                            up vote
                            0
                            down vote









                            This should do the trick:



                            let keys = ['a','b','c','d']
                            let values = [1,2,3,4]
                            let mapped = keys.reduce((accumulator, current, index) => {
                            accumulator[current] = values[index];
                            return accumulator;
                            }, {});

                            console.log(mapped)
                            // Result should be:
                            {a: 1, b: 2, c: 3, d: 4}


                            Reduce is a powerful method that can be used for all sorts of tasks.



                            Here we're "reducing" the given values of keys into an object where keys are the key and values are the correlating values.



                            The first parameter in reduce is a callback function that you need to pass along at minimum accumulator and current variables (can have different names); the other parameters are index and array which represent the current index of the iteration and the original array that is being iterated.



                            The second parameter is the initial value of the accumulator; by default it will be the first current value but in our case we set it to {} so we can treat it as an object.



                            I hope this helps!






                            share|improve this answer












                            This should do the trick:



                            let keys = ['a','b','c','d']
                            let values = [1,2,3,4]
                            let mapped = keys.reduce((accumulator, current, index) => {
                            accumulator[current] = values[index];
                            return accumulator;
                            }, {});

                            console.log(mapped)
                            // Result should be:
                            {a: 1, b: 2, c: 3, d: 4}


                            Reduce is a powerful method that can be used for all sorts of tasks.



                            Here we're "reducing" the given values of keys into an object where keys are the key and values are the correlating values.



                            The first parameter in reduce is a callback function that you need to pass along at minimum accumulator and current variables (can have different names); the other parameters are index and array which represent the current index of the iteration and the original array that is being iterated.



                            The second parameter is the initial value of the accumulator; by default it will be the first current value but in our case we set it to {} so we can treat it as an object.



                            I hope this helps!







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 9 at 16:52









                            Erik Withak

                            125




                            125






























                                 

                                draft saved


                                draft discarded



















































                                 


                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53229659%2fjavascript-converting-2-string-arrays-to-map%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Schultheiß

                                Verwaltungsgliederung Dänemarks

                                Liste der Kulturdenkmale in Wilsdruff