Add key to array in javascript











up vote
1
down vote

favorite












I have an array of data, with first line being a header:



[["Date", "Key1", "Key2", "Key3", "Key4"],
["2018-11-01", "254", "-", "-", "-"],
["2018-11-02", "648", "-", "-", "-"],
["2018-11-03", "270", "170", "-", "147"],
["2018-11-04", "300", "406", "136", "208"]]


The output I would like to have to be able to use it with a D3 library graph would be:



[[Date: "2018-11-01", Key1: "254", Key2: "-", Key3: "-", Key4: "-"],
[Date: "2018-11-02", Key1: "648", Key2: "-", Key3: "-", Key4: "-"],
[Date: "2018-11-03", Key1: "270", Key2: "170", Key3: "-", Key4: "147"],
[Date: "2018-11-04", Key1: "300", Key2: "406", Key3: "136", Key4: "208"]]


I tried many unsuccessful variations to do that with javascript, using map. but I can't manage to do it... Keys are dynamic so I can't use fixed keys.
Can someone help me?
Thank you!
Manue










share|improve this question


















  • 2




    seems like a map and a forEach/reduce.... Show what you tried that failed
    – epascarello
    Nov 19 at 15:32

















up vote
1
down vote

favorite












I have an array of data, with first line being a header:



[["Date", "Key1", "Key2", "Key3", "Key4"],
["2018-11-01", "254", "-", "-", "-"],
["2018-11-02", "648", "-", "-", "-"],
["2018-11-03", "270", "170", "-", "147"],
["2018-11-04", "300", "406", "136", "208"]]


The output I would like to have to be able to use it with a D3 library graph would be:



[[Date: "2018-11-01", Key1: "254", Key2: "-", Key3: "-", Key4: "-"],
[Date: "2018-11-02", Key1: "648", Key2: "-", Key3: "-", Key4: "-"],
[Date: "2018-11-03", Key1: "270", Key2: "170", Key3: "-", Key4: "147"],
[Date: "2018-11-04", Key1: "300", Key2: "406", Key3: "136", Key4: "208"]]


I tried many unsuccessful variations to do that with javascript, using map. but I can't manage to do it... Keys are dynamic so I can't use fixed keys.
Can someone help me?
Thank you!
Manue










share|improve this question


















  • 2




    seems like a map and a forEach/reduce.... Show what you tried that failed
    – epascarello
    Nov 19 at 15:32















up vote
1
down vote

favorite









up vote
1
down vote

favorite











I have an array of data, with first line being a header:



[["Date", "Key1", "Key2", "Key3", "Key4"],
["2018-11-01", "254", "-", "-", "-"],
["2018-11-02", "648", "-", "-", "-"],
["2018-11-03", "270", "170", "-", "147"],
["2018-11-04", "300", "406", "136", "208"]]


The output I would like to have to be able to use it with a D3 library graph would be:



[[Date: "2018-11-01", Key1: "254", Key2: "-", Key3: "-", Key4: "-"],
[Date: "2018-11-02", Key1: "648", Key2: "-", Key3: "-", Key4: "-"],
[Date: "2018-11-03", Key1: "270", Key2: "170", Key3: "-", Key4: "147"],
[Date: "2018-11-04", Key1: "300", Key2: "406", Key3: "136", Key4: "208"]]


I tried many unsuccessful variations to do that with javascript, using map. but I can't manage to do it... Keys are dynamic so I can't use fixed keys.
Can someone help me?
Thank you!
Manue










share|improve this question













I have an array of data, with first line being a header:



[["Date", "Key1", "Key2", "Key3", "Key4"],
["2018-11-01", "254", "-", "-", "-"],
["2018-11-02", "648", "-", "-", "-"],
["2018-11-03", "270", "170", "-", "147"],
["2018-11-04", "300", "406", "136", "208"]]


The output I would like to have to be able to use it with a D3 library graph would be:



[[Date: "2018-11-01", Key1: "254", Key2: "-", Key3: "-", Key4: "-"],
[Date: "2018-11-02", Key1: "648", Key2: "-", Key3: "-", Key4: "-"],
[Date: "2018-11-03", Key1: "270", Key2: "170", Key3: "-", Key4: "147"],
[Date: "2018-11-04", Key1: "300", Key2: "406", Key3: "136", Key4: "208"]]


I tried many unsuccessful variations to do that with javascript, using map. but I can't manage to do it... Keys are dynamic so I can't use fixed keys.
Can someone help me?
Thank you!
Manue







javascript arrays multidimensional-array






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 19 at 15:29









Tiwelle

386




386








  • 2




    seems like a map and a forEach/reduce.... Show what you tried that failed
    – epascarello
    Nov 19 at 15:32
















  • 2




    seems like a map and a forEach/reduce.... Show what you tried that failed
    – epascarello
    Nov 19 at 15:32










2




2




seems like a map and a forEach/reduce.... Show what you tried that failed
– epascarello
Nov 19 at 15:32






seems like a map and a forEach/reduce.... Show what you tried that failed
– epascarello
Nov 19 at 15:32














3 Answers
3






active

oldest

votes

















up vote
2
down vote



accepted










For an array of objects, you could map the values and take mapped objects, which are assigned to a single object.






var data = [["Date", "Key1", "Key2", "Key3", "Key4"], ["2018-11-01", "254", "-", "-", "-"], ["2018-11-02", "648", "-", "-", "-"], ["2018-11-03", "270", "170", "-", "147"], ["2018-11-04", "300", "406", "136", "208"]],
result = data.slice(1).map(a => Object.assign(...a.map((v, i) => ({ [data[0][i]]: v }))));

console.log(result);

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








share|improve this answer























  • Thank you very much! That works exactly as expected!
    – Tiwelle
    Nov 20 at 9:58


















up vote
0
down vote













You need to map your inner arrays to objects. You cannot assign key-value pairs within an array construct.






var matrix = [
[ "Date", "Key1", "Key2", "Key3", "Key4" ],
[ "2018-11-01", "254", "-", "-", "-" ],
[ "2018-11-02", "648", "-", "-", "-" ],
[ "2018-11-03", "270", "170", "-", "147" ],
[ "2018-11-04", "300", "406", "136", "208" ]
];

console.log(JSON.stringify(matrixToJsonObjectArray(matrix, true), null, 2));

function matrixToJsonObjectArray(matrix, includesHeader) {
var fields = includesHeader ? matrix[0] : range(matrix[0].length);
return (includesHeader ? matrix.slice(1) : matrix).map(row => {
var obj = {};
fields.forEach((field, i) => obj[field] = row[i]);
return obj;
});
}

function range(start, end) {
var arr = ;
if (end === undefined) end = start, start = 0;
for (var i = start; i < end; i++) arr.push(i);
return arr;
}

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








share|improve this answer




























    up vote
    0
    down vote













    You can create a zipObject method that converts to arrays to object using Array.reduce(), and use it with Array.map() to combine the header array, with the other arrays:






    const data = [["Date", "Key1", "Key2", "Key3", "Key4"], ["2018-11-01", "254", "-", "-", "-"], ["2018-11-02", "648", "-", "-", "-"], ["2018-11-03", "270", "170", "-", "147"], ["2018-11-04", "300", "406", "136", "208"]];

    // zip two arrays to an object
    const zipObject = (keys) => (values) =>
    keys.reduce((r, key, i) => ({ ...r, [key]: values[i] }), {});

    // convert a two dimensional array to object
    const arrToObj = ([keys, ...values]) => values.map(zipObject(keys));

    const result = arrToObj(data);

    console.log(result);

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








    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%2f53377856%2fadd-key-to-array-in-javascript%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      2
      down vote



      accepted










      For an array of objects, you could map the values and take mapped objects, which are assigned to a single object.






      var data = [["Date", "Key1", "Key2", "Key3", "Key4"], ["2018-11-01", "254", "-", "-", "-"], ["2018-11-02", "648", "-", "-", "-"], ["2018-11-03", "270", "170", "-", "147"], ["2018-11-04", "300", "406", "136", "208"]],
      result = data.slice(1).map(a => Object.assign(...a.map((v, i) => ({ [data[0][i]]: v }))));

      console.log(result);

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








      share|improve this answer























      • Thank you very much! That works exactly as expected!
        – Tiwelle
        Nov 20 at 9:58















      up vote
      2
      down vote



      accepted










      For an array of objects, you could map the values and take mapped objects, which are assigned to a single object.






      var data = [["Date", "Key1", "Key2", "Key3", "Key4"], ["2018-11-01", "254", "-", "-", "-"], ["2018-11-02", "648", "-", "-", "-"], ["2018-11-03", "270", "170", "-", "147"], ["2018-11-04", "300", "406", "136", "208"]],
      result = data.slice(1).map(a => Object.assign(...a.map((v, i) => ({ [data[0][i]]: v }))));

      console.log(result);

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








      share|improve this answer























      • Thank you very much! That works exactly as expected!
        – Tiwelle
        Nov 20 at 9:58













      up vote
      2
      down vote



      accepted







      up vote
      2
      down vote



      accepted






      For an array of objects, you could map the values and take mapped objects, which are assigned to a single object.






      var data = [["Date", "Key1", "Key2", "Key3", "Key4"], ["2018-11-01", "254", "-", "-", "-"], ["2018-11-02", "648", "-", "-", "-"], ["2018-11-03", "270", "170", "-", "147"], ["2018-11-04", "300", "406", "136", "208"]],
      result = data.slice(1).map(a => Object.assign(...a.map((v, i) => ({ [data[0][i]]: v }))));

      console.log(result);

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








      share|improve this answer














      For an array of objects, you could map the values and take mapped objects, which are assigned to a single object.






      var data = [["Date", "Key1", "Key2", "Key3", "Key4"], ["2018-11-01", "254", "-", "-", "-"], ["2018-11-02", "648", "-", "-", "-"], ["2018-11-03", "270", "170", "-", "147"], ["2018-11-04", "300", "406", "136", "208"]],
      result = data.slice(1).map(a => Object.assign(...a.map((v, i) => ({ [data[0][i]]: v }))));

      console.log(result);

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








      var data = [["Date", "Key1", "Key2", "Key3", "Key4"], ["2018-11-01", "254", "-", "-", "-"], ["2018-11-02", "648", "-", "-", "-"], ["2018-11-03", "270", "170", "-", "147"], ["2018-11-04", "300", "406", "136", "208"]],
      result = data.slice(1).map(a => Object.assign(...a.map((v, i) => ({ [data[0][i]]: v }))));

      console.log(result);

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





      var data = [["Date", "Key1", "Key2", "Key3", "Key4"], ["2018-11-01", "254", "-", "-", "-"], ["2018-11-02", "648", "-", "-", "-"], ["2018-11-03", "270", "170", "-", "147"], ["2018-11-04", "300", "406", "136", "208"]],
      result = data.slice(1).map(a => Object.assign(...a.map((v, i) => ({ [data[0][i]]: v }))));

      console.log(result);

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






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 19 at 15:34









      Ori Drori

      71.8k127589




      71.8k127589










      answered Nov 19 at 15:33









      Nina Scholz

      172k1384147




      172k1384147












      • Thank you very much! That works exactly as expected!
        – Tiwelle
        Nov 20 at 9:58


















      • Thank you very much! That works exactly as expected!
        – Tiwelle
        Nov 20 at 9:58
















      Thank you very much! That works exactly as expected!
      – Tiwelle
      Nov 20 at 9:58




      Thank you very much! That works exactly as expected!
      – Tiwelle
      Nov 20 at 9:58












      up vote
      0
      down vote













      You need to map your inner arrays to objects. You cannot assign key-value pairs within an array construct.






      var matrix = [
      [ "Date", "Key1", "Key2", "Key3", "Key4" ],
      [ "2018-11-01", "254", "-", "-", "-" ],
      [ "2018-11-02", "648", "-", "-", "-" ],
      [ "2018-11-03", "270", "170", "-", "147" ],
      [ "2018-11-04", "300", "406", "136", "208" ]
      ];

      console.log(JSON.stringify(matrixToJsonObjectArray(matrix, true), null, 2));

      function matrixToJsonObjectArray(matrix, includesHeader) {
      var fields = includesHeader ? matrix[0] : range(matrix[0].length);
      return (includesHeader ? matrix.slice(1) : matrix).map(row => {
      var obj = {};
      fields.forEach((field, i) => obj[field] = row[i]);
      return obj;
      });
      }

      function range(start, end) {
      var arr = ;
      if (end === undefined) end = start, start = 0;
      for (var i = start; i < end; i++) arr.push(i);
      return arr;
      }

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








      share|improve this answer

























        up vote
        0
        down vote













        You need to map your inner arrays to objects. You cannot assign key-value pairs within an array construct.






        var matrix = [
        [ "Date", "Key1", "Key2", "Key3", "Key4" ],
        [ "2018-11-01", "254", "-", "-", "-" ],
        [ "2018-11-02", "648", "-", "-", "-" ],
        [ "2018-11-03", "270", "170", "-", "147" ],
        [ "2018-11-04", "300", "406", "136", "208" ]
        ];

        console.log(JSON.stringify(matrixToJsonObjectArray(matrix, true), null, 2));

        function matrixToJsonObjectArray(matrix, includesHeader) {
        var fields = includesHeader ? matrix[0] : range(matrix[0].length);
        return (includesHeader ? matrix.slice(1) : matrix).map(row => {
        var obj = {};
        fields.forEach((field, i) => obj[field] = row[i]);
        return obj;
        });
        }

        function range(start, end) {
        var arr = ;
        if (end === undefined) end = start, start = 0;
        for (var i = start; i < end; i++) arr.push(i);
        return arr;
        }

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








        share|improve this answer























          up vote
          0
          down vote










          up vote
          0
          down vote









          You need to map your inner arrays to objects. You cannot assign key-value pairs within an array construct.






          var matrix = [
          [ "Date", "Key1", "Key2", "Key3", "Key4" ],
          [ "2018-11-01", "254", "-", "-", "-" ],
          [ "2018-11-02", "648", "-", "-", "-" ],
          [ "2018-11-03", "270", "170", "-", "147" ],
          [ "2018-11-04", "300", "406", "136", "208" ]
          ];

          console.log(JSON.stringify(matrixToJsonObjectArray(matrix, true), null, 2));

          function matrixToJsonObjectArray(matrix, includesHeader) {
          var fields = includesHeader ? matrix[0] : range(matrix[0].length);
          return (includesHeader ? matrix.slice(1) : matrix).map(row => {
          var obj = {};
          fields.forEach((field, i) => obj[field] = row[i]);
          return obj;
          });
          }

          function range(start, end) {
          var arr = ;
          if (end === undefined) end = start, start = 0;
          for (var i = start; i < end; i++) arr.push(i);
          return arr;
          }

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








          share|improve this answer












          You need to map your inner arrays to objects. You cannot assign key-value pairs within an array construct.






          var matrix = [
          [ "Date", "Key1", "Key2", "Key3", "Key4" ],
          [ "2018-11-01", "254", "-", "-", "-" ],
          [ "2018-11-02", "648", "-", "-", "-" ],
          [ "2018-11-03", "270", "170", "-", "147" ],
          [ "2018-11-04", "300", "406", "136", "208" ]
          ];

          console.log(JSON.stringify(matrixToJsonObjectArray(matrix, true), null, 2));

          function matrixToJsonObjectArray(matrix, includesHeader) {
          var fields = includesHeader ? matrix[0] : range(matrix[0].length);
          return (includesHeader ? matrix.slice(1) : matrix).map(row => {
          var obj = {};
          fields.forEach((field, i) => obj[field] = row[i]);
          return obj;
          });
          }

          function range(start, end) {
          var arr = ;
          if (end === undefined) end = start, start = 0;
          for (var i = start; i < end; i++) arr.push(i);
          return arr;
          }

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








          var matrix = [
          [ "Date", "Key1", "Key2", "Key3", "Key4" ],
          [ "2018-11-01", "254", "-", "-", "-" ],
          [ "2018-11-02", "648", "-", "-", "-" ],
          [ "2018-11-03", "270", "170", "-", "147" ],
          [ "2018-11-04", "300", "406", "136", "208" ]
          ];

          console.log(JSON.stringify(matrixToJsonObjectArray(matrix, true), null, 2));

          function matrixToJsonObjectArray(matrix, includesHeader) {
          var fields = includesHeader ? matrix[0] : range(matrix[0].length);
          return (includesHeader ? matrix.slice(1) : matrix).map(row => {
          var obj = {};
          fields.forEach((field, i) => obj[field] = row[i]);
          return obj;
          });
          }

          function range(start, end) {
          var arr = ;
          if (end === undefined) end = start, start = 0;
          for (var i = start; i < end; i++) arr.push(i);
          return arr;
          }

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





          var matrix = [
          [ "Date", "Key1", "Key2", "Key3", "Key4" ],
          [ "2018-11-01", "254", "-", "-", "-" ],
          [ "2018-11-02", "648", "-", "-", "-" ],
          [ "2018-11-03", "270", "170", "-", "147" ],
          [ "2018-11-04", "300", "406", "136", "208" ]
          ];

          console.log(JSON.stringify(matrixToJsonObjectArray(matrix, true), null, 2));

          function matrixToJsonObjectArray(matrix, includesHeader) {
          var fields = includesHeader ? matrix[0] : range(matrix[0].length);
          return (includesHeader ? matrix.slice(1) : matrix).map(row => {
          var obj = {};
          fields.forEach((field, i) => obj[field] = row[i]);
          return obj;
          });
          }

          function range(start, end) {
          var arr = ;
          if (end === undefined) end = start, start = 0;
          for (var i = start; i < end; i++) arr.push(i);
          return arr;
          }

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






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 19 at 15:39









          Mr. Polywhirl

          16.2k84883




          16.2k84883






















              up vote
              0
              down vote













              You can create a zipObject method that converts to arrays to object using Array.reduce(), and use it with Array.map() to combine the header array, with the other arrays:






              const data = [["Date", "Key1", "Key2", "Key3", "Key4"], ["2018-11-01", "254", "-", "-", "-"], ["2018-11-02", "648", "-", "-", "-"], ["2018-11-03", "270", "170", "-", "147"], ["2018-11-04", "300", "406", "136", "208"]];

              // zip two arrays to an object
              const zipObject = (keys) => (values) =>
              keys.reduce((r, key, i) => ({ ...r, [key]: values[i] }), {});

              // convert a two dimensional array to object
              const arrToObj = ([keys, ...values]) => values.map(zipObject(keys));

              const result = arrToObj(data);

              console.log(result);

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








              share|improve this answer

























                up vote
                0
                down vote













                You can create a zipObject method that converts to arrays to object using Array.reduce(), and use it with Array.map() to combine the header array, with the other arrays:






                const data = [["Date", "Key1", "Key2", "Key3", "Key4"], ["2018-11-01", "254", "-", "-", "-"], ["2018-11-02", "648", "-", "-", "-"], ["2018-11-03", "270", "170", "-", "147"], ["2018-11-04", "300", "406", "136", "208"]];

                // zip two arrays to an object
                const zipObject = (keys) => (values) =>
                keys.reduce((r, key, i) => ({ ...r, [key]: values[i] }), {});

                // convert a two dimensional array to object
                const arrToObj = ([keys, ...values]) => values.map(zipObject(keys));

                const result = arrToObj(data);

                console.log(result);

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








                share|improve this answer























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  You can create a zipObject method that converts to arrays to object using Array.reduce(), and use it with Array.map() to combine the header array, with the other arrays:






                  const data = [["Date", "Key1", "Key2", "Key3", "Key4"], ["2018-11-01", "254", "-", "-", "-"], ["2018-11-02", "648", "-", "-", "-"], ["2018-11-03", "270", "170", "-", "147"], ["2018-11-04", "300", "406", "136", "208"]];

                  // zip two arrays to an object
                  const zipObject = (keys) => (values) =>
                  keys.reduce((r, key, i) => ({ ...r, [key]: values[i] }), {});

                  // convert a two dimensional array to object
                  const arrToObj = ([keys, ...values]) => values.map(zipObject(keys));

                  const result = arrToObj(data);

                  console.log(result);

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








                  share|improve this answer












                  You can create a zipObject method that converts to arrays to object using Array.reduce(), and use it with Array.map() to combine the header array, with the other arrays:






                  const data = [["Date", "Key1", "Key2", "Key3", "Key4"], ["2018-11-01", "254", "-", "-", "-"], ["2018-11-02", "648", "-", "-", "-"], ["2018-11-03", "270", "170", "-", "147"], ["2018-11-04", "300", "406", "136", "208"]];

                  // zip two arrays to an object
                  const zipObject = (keys) => (values) =>
                  keys.reduce((r, key, i) => ({ ...r, [key]: values[i] }), {});

                  // convert a two dimensional array to object
                  const arrToObj = ([keys, ...values]) => values.map(zipObject(keys));

                  const result = arrToObj(data);

                  console.log(result);

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








                  const data = [["Date", "Key1", "Key2", "Key3", "Key4"], ["2018-11-01", "254", "-", "-", "-"], ["2018-11-02", "648", "-", "-", "-"], ["2018-11-03", "270", "170", "-", "147"], ["2018-11-04", "300", "406", "136", "208"]];

                  // zip two arrays to an object
                  const zipObject = (keys) => (values) =>
                  keys.reduce((r, key, i) => ({ ...r, [key]: values[i] }), {});

                  // convert a two dimensional array to object
                  const arrToObj = ([keys, ...values]) => values.map(zipObject(keys));

                  const result = arrToObj(data);

                  console.log(result);

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





                  const data = [["Date", "Key1", "Key2", "Key3", "Key4"], ["2018-11-01", "254", "-", "-", "-"], ["2018-11-02", "648", "-", "-", "-"], ["2018-11-03", "270", "170", "-", "147"], ["2018-11-04", "300", "406", "136", "208"]];

                  // zip two arrays to an object
                  const zipObject = (keys) => (values) =>
                  keys.reduce((r, key, i) => ({ ...r, [key]: values[i] }), {});

                  // convert a two dimensional array to object
                  const arrToObj = ([keys, ...values]) => values.map(zipObject(keys));

                  const result = arrToObj(data);

                  console.log(result);

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






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 19 at 15:41









                  Ori Drori

                  71.8k127589




                  71.8k127589






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53377856%2fadd-key-to-array-in-javascript%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

                      Create new schema in PostgreSQL using DBeaver

                      Deepest pit of an array with Javascript: test on Codility

                      Costa Masnaga