If non-array property exists convert it to one and push new value












4












$begingroup$


Is there a simpler/shorter/better way to do this?



let obj={a:1,b:[1,2]}

function add(key,value){
if(!obj[key].push){
obj[key]=[obj[key]]
}
obj[key].push(value)
}









share|improve this question











$endgroup$

















    4












    $begingroup$


    Is there a simpler/shorter/better way to do this?



    let obj={a:1,b:[1,2]}

    function add(key,value){
    if(!obj[key].push){
    obj[key]=[obj[key]]
    }
    obj[key].push(value)
    }









    share|improve this question











    $endgroup$















      4












      4








      4





      $begingroup$


      Is there a simpler/shorter/better way to do this?



      let obj={a:1,b:[1,2]}

      function add(key,value){
      if(!obj[key].push){
      obj[key]=[obj[key]]
      }
      obj[key].push(value)
      }









      share|improve this question











      $endgroup$




      Is there a simpler/shorter/better way to do this?



      let obj={a:1,b:[1,2]}

      function add(key,value){
      if(!obj[key].push){
      obj[key]=[obj[key]]
      }
      obj[key].push(value)
      }






      javascript array ecmascript-6 properties






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Dec 20 '18 at 19:18









      Sᴀᴍ Onᴇᴌᴀ

      9,90162165




      9,90162165










      asked Oct 3 '17 at 20:06









      qw3nqw3n

      1234




      1234






















          2 Answers
          2






          active

          oldest

          votes


















          9












          $begingroup$

          Basically after reading over the code, I interpret that the conditional (i.e. !obj[key].push) checks if the value at the given key is not an array. A more robust way to do that is to use (the negated value of) Array.isArray() instead. That may not be any shorter, but perhaps a better way to determine if the property at key is an array.






          var obj={a:1,b:[1,2]}

          function add(key,value){
          if(!Array.isArray(obj[key])){
          obj[key]=[obj[key]]
          }
          obj[key].push(value)
          }
          add('a',3);
          console.log(obj);





          It would be difficult to prevent the re-assignment of .push (see example below). .push could be assigned to something other than a function, like an integer, string or object, or a function that does something other than push the supplied argument on the array.






          var obj={a:1,b:[1,2]}

          function add(key,value){
          if(!obj[key].push){
          obj[key]=[obj[key]]
          }
          obj[key].push(value)
          }
          obj.b.push = undefined;
          add('b',3);
          console.log(obj);





          Edit



          insertusernamehere made a good point in a comment: Perhaps it would be wise to guard against the case where the obj[key] is undefined. The current code would add that to the array, which is likely not preferable.



          There are multiple ways to do this, including calling obj.hasOwnProperty(), checking the array returned by Object.keys(obj) does include key, etc.






          var obj={a:1,b:[1,2]}

          function add(key,value){
          if (!Object.hasOwnProperty(key)) {
          obj[key]=;
          }
          if(!Array.isArray(obj[key])){
          obj[key]=[obj[key]]
          }
          obj[key].push(value)
          }
          add('a',3);
          add('c',4);
          console.log(obj);








          share|improve this answer











          $endgroup$









          • 4




            $begingroup$
            I like your answer. I don't think that one should bother with possible reassignment of push, since a) it's an absolutely cornerstone method on arrays and messing with it will lead to deadly daemons; b) the add(...) function depends on that heavily (a spread operator could be a work around instead of a push for inserts, but it's potentially much costlier, especially on large arrays). The only "real" question here is "how to reliably identify an array in JavaScript", IMO.
            $endgroup$
            – Igor Soloydenko
            Oct 3 '17 at 20:37












          • $begingroup$
            @IgorSoloydenko so is what your saying that unless you use spread syntax this is probably the best way of doing it? And if you do use spread syntax their would be a definite performance penalty?
            $endgroup$
            – qw3n
            Oct 3 '17 at 20:57










          • $begingroup$
            Yes, you read me correctly. [...someArray, newValue] will iterate over someArray's values to produce a new array. So it's by definition somewhat costlier. This may or may not be a big deal for you. Btw, I'm can't guarantee that ... is not using .push() under the hood... And I can't see any problems in what you and Sam are having in your code snippets.
            $endgroup$
            – Igor Soloydenko
            Oct 3 '17 at 21:01






          • 2




            $begingroup$
            Maybe worth mentioning: The OP's and this solution don't test whether the key exists at all. If it doesn't, it will add an undefined value to the newly created array, for example when calling add('x', 1).
            $endgroup$
            – insertusernamehere
            Oct 3 '17 at 23:03






          • 1




            $begingroup$
            yeah - I guess I have an aversion to it now because of a linter used on a project at work that complains whenever it finds calls to .hasOwnProperty() but that is simpler.
            $endgroup$
            – Sᴀᴍ Onᴇᴌᴀ
            Oct 3 '17 at 23:50





















          2












          $begingroup$

          Another possible way is to use concat instead of push. You may still want to do a hasOwnProperty check to ensure the property exists.



          function add(key,value) {
          if (!obj.hasOwnProperty(key)) {
          obj[key]=;
          }

          obj[key] = .concat(obj[key], value);
          }





          share|improve this answer









          $endgroup$













            Your Answer





            StackExchange.ifUsing("editor", function () {
            return StackExchange.using("mathjaxEditing", function () {
            StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
            StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
            });
            });
            }, "mathjax-editing");

            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: "196"
            };
            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',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            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%2fcodereview.stackexchange.com%2fquestions%2f177090%2fif-non-array-property-exists-convert-it-to-one-and-push-new-value%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            9












            $begingroup$

            Basically after reading over the code, I interpret that the conditional (i.e. !obj[key].push) checks if the value at the given key is not an array. A more robust way to do that is to use (the negated value of) Array.isArray() instead. That may not be any shorter, but perhaps a better way to determine if the property at key is an array.






            var obj={a:1,b:[1,2]}

            function add(key,value){
            if(!Array.isArray(obj[key])){
            obj[key]=[obj[key]]
            }
            obj[key].push(value)
            }
            add('a',3);
            console.log(obj);





            It would be difficult to prevent the re-assignment of .push (see example below). .push could be assigned to something other than a function, like an integer, string or object, or a function that does something other than push the supplied argument on the array.






            var obj={a:1,b:[1,2]}

            function add(key,value){
            if(!obj[key].push){
            obj[key]=[obj[key]]
            }
            obj[key].push(value)
            }
            obj.b.push = undefined;
            add('b',3);
            console.log(obj);





            Edit



            insertusernamehere made a good point in a comment: Perhaps it would be wise to guard against the case where the obj[key] is undefined. The current code would add that to the array, which is likely not preferable.



            There are multiple ways to do this, including calling obj.hasOwnProperty(), checking the array returned by Object.keys(obj) does include key, etc.






            var obj={a:1,b:[1,2]}

            function add(key,value){
            if (!Object.hasOwnProperty(key)) {
            obj[key]=;
            }
            if(!Array.isArray(obj[key])){
            obj[key]=[obj[key]]
            }
            obj[key].push(value)
            }
            add('a',3);
            add('c',4);
            console.log(obj);








            share|improve this answer











            $endgroup$









            • 4




              $begingroup$
              I like your answer. I don't think that one should bother with possible reassignment of push, since a) it's an absolutely cornerstone method on arrays and messing with it will lead to deadly daemons; b) the add(...) function depends on that heavily (a spread operator could be a work around instead of a push for inserts, but it's potentially much costlier, especially on large arrays). The only "real" question here is "how to reliably identify an array in JavaScript", IMO.
              $endgroup$
              – Igor Soloydenko
              Oct 3 '17 at 20:37












            • $begingroup$
              @IgorSoloydenko so is what your saying that unless you use spread syntax this is probably the best way of doing it? And if you do use spread syntax their would be a definite performance penalty?
              $endgroup$
              – qw3n
              Oct 3 '17 at 20:57










            • $begingroup$
              Yes, you read me correctly. [...someArray, newValue] will iterate over someArray's values to produce a new array. So it's by definition somewhat costlier. This may or may not be a big deal for you. Btw, I'm can't guarantee that ... is not using .push() under the hood... And I can't see any problems in what you and Sam are having in your code snippets.
              $endgroup$
              – Igor Soloydenko
              Oct 3 '17 at 21:01






            • 2




              $begingroup$
              Maybe worth mentioning: The OP's and this solution don't test whether the key exists at all. If it doesn't, it will add an undefined value to the newly created array, for example when calling add('x', 1).
              $endgroup$
              – insertusernamehere
              Oct 3 '17 at 23:03






            • 1




              $begingroup$
              yeah - I guess I have an aversion to it now because of a linter used on a project at work that complains whenever it finds calls to .hasOwnProperty() but that is simpler.
              $endgroup$
              – Sᴀᴍ Onᴇᴌᴀ
              Oct 3 '17 at 23:50


















            9












            $begingroup$

            Basically after reading over the code, I interpret that the conditional (i.e. !obj[key].push) checks if the value at the given key is not an array. A more robust way to do that is to use (the negated value of) Array.isArray() instead. That may not be any shorter, but perhaps a better way to determine if the property at key is an array.






            var obj={a:1,b:[1,2]}

            function add(key,value){
            if(!Array.isArray(obj[key])){
            obj[key]=[obj[key]]
            }
            obj[key].push(value)
            }
            add('a',3);
            console.log(obj);





            It would be difficult to prevent the re-assignment of .push (see example below). .push could be assigned to something other than a function, like an integer, string or object, or a function that does something other than push the supplied argument on the array.






            var obj={a:1,b:[1,2]}

            function add(key,value){
            if(!obj[key].push){
            obj[key]=[obj[key]]
            }
            obj[key].push(value)
            }
            obj.b.push = undefined;
            add('b',3);
            console.log(obj);





            Edit



            insertusernamehere made a good point in a comment: Perhaps it would be wise to guard against the case where the obj[key] is undefined. The current code would add that to the array, which is likely not preferable.



            There are multiple ways to do this, including calling obj.hasOwnProperty(), checking the array returned by Object.keys(obj) does include key, etc.






            var obj={a:1,b:[1,2]}

            function add(key,value){
            if (!Object.hasOwnProperty(key)) {
            obj[key]=;
            }
            if(!Array.isArray(obj[key])){
            obj[key]=[obj[key]]
            }
            obj[key].push(value)
            }
            add('a',3);
            add('c',4);
            console.log(obj);








            share|improve this answer











            $endgroup$









            • 4




              $begingroup$
              I like your answer. I don't think that one should bother with possible reassignment of push, since a) it's an absolutely cornerstone method on arrays and messing with it will lead to deadly daemons; b) the add(...) function depends on that heavily (a spread operator could be a work around instead of a push for inserts, but it's potentially much costlier, especially on large arrays). The only "real" question here is "how to reliably identify an array in JavaScript", IMO.
              $endgroup$
              – Igor Soloydenko
              Oct 3 '17 at 20:37












            • $begingroup$
              @IgorSoloydenko so is what your saying that unless you use spread syntax this is probably the best way of doing it? And if you do use spread syntax their would be a definite performance penalty?
              $endgroup$
              – qw3n
              Oct 3 '17 at 20:57










            • $begingroup$
              Yes, you read me correctly. [...someArray, newValue] will iterate over someArray's values to produce a new array. So it's by definition somewhat costlier. This may or may not be a big deal for you. Btw, I'm can't guarantee that ... is not using .push() under the hood... And I can't see any problems in what you and Sam are having in your code snippets.
              $endgroup$
              – Igor Soloydenko
              Oct 3 '17 at 21:01






            • 2




              $begingroup$
              Maybe worth mentioning: The OP's and this solution don't test whether the key exists at all. If it doesn't, it will add an undefined value to the newly created array, for example when calling add('x', 1).
              $endgroup$
              – insertusernamehere
              Oct 3 '17 at 23:03






            • 1




              $begingroup$
              yeah - I guess I have an aversion to it now because of a linter used on a project at work that complains whenever it finds calls to .hasOwnProperty() but that is simpler.
              $endgroup$
              – Sᴀᴍ Onᴇᴌᴀ
              Oct 3 '17 at 23:50
















            9












            9








            9





            $begingroup$

            Basically after reading over the code, I interpret that the conditional (i.e. !obj[key].push) checks if the value at the given key is not an array. A more robust way to do that is to use (the negated value of) Array.isArray() instead. That may not be any shorter, but perhaps a better way to determine if the property at key is an array.






            var obj={a:1,b:[1,2]}

            function add(key,value){
            if(!Array.isArray(obj[key])){
            obj[key]=[obj[key]]
            }
            obj[key].push(value)
            }
            add('a',3);
            console.log(obj);





            It would be difficult to prevent the re-assignment of .push (see example below). .push could be assigned to something other than a function, like an integer, string or object, or a function that does something other than push the supplied argument on the array.






            var obj={a:1,b:[1,2]}

            function add(key,value){
            if(!obj[key].push){
            obj[key]=[obj[key]]
            }
            obj[key].push(value)
            }
            obj.b.push = undefined;
            add('b',3);
            console.log(obj);





            Edit



            insertusernamehere made a good point in a comment: Perhaps it would be wise to guard against the case where the obj[key] is undefined. The current code would add that to the array, which is likely not preferable.



            There are multiple ways to do this, including calling obj.hasOwnProperty(), checking the array returned by Object.keys(obj) does include key, etc.






            var obj={a:1,b:[1,2]}

            function add(key,value){
            if (!Object.hasOwnProperty(key)) {
            obj[key]=;
            }
            if(!Array.isArray(obj[key])){
            obj[key]=[obj[key]]
            }
            obj[key].push(value)
            }
            add('a',3);
            add('c',4);
            console.log(obj);








            share|improve this answer











            $endgroup$



            Basically after reading over the code, I interpret that the conditional (i.e. !obj[key].push) checks if the value at the given key is not an array. A more robust way to do that is to use (the negated value of) Array.isArray() instead. That may not be any shorter, but perhaps a better way to determine if the property at key is an array.






            var obj={a:1,b:[1,2]}

            function add(key,value){
            if(!Array.isArray(obj[key])){
            obj[key]=[obj[key]]
            }
            obj[key].push(value)
            }
            add('a',3);
            console.log(obj);





            It would be difficult to prevent the re-assignment of .push (see example below). .push could be assigned to something other than a function, like an integer, string or object, or a function that does something other than push the supplied argument on the array.






            var obj={a:1,b:[1,2]}

            function add(key,value){
            if(!obj[key].push){
            obj[key]=[obj[key]]
            }
            obj[key].push(value)
            }
            obj.b.push = undefined;
            add('b',3);
            console.log(obj);





            Edit



            insertusernamehere made a good point in a comment: Perhaps it would be wise to guard against the case where the obj[key] is undefined. The current code would add that to the array, which is likely not preferable.



            There are multiple ways to do this, including calling obj.hasOwnProperty(), checking the array returned by Object.keys(obj) does include key, etc.






            var obj={a:1,b:[1,2]}

            function add(key,value){
            if (!Object.hasOwnProperty(key)) {
            obj[key]=;
            }
            if(!Array.isArray(obj[key])){
            obj[key]=[obj[key]]
            }
            obj[key].push(value)
            }
            add('a',3);
            add('c',4);
            console.log(obj);








            var obj={a:1,b:[1,2]}

            function add(key,value){
            if(!Array.isArray(obj[key])){
            obj[key]=[obj[key]]
            }
            obj[key].push(value)
            }
            add('a',3);
            console.log(obj);





            var obj={a:1,b:[1,2]}

            function add(key,value){
            if(!Array.isArray(obj[key])){
            obj[key]=[obj[key]]
            }
            obj[key].push(value)
            }
            add('a',3);
            console.log(obj);





            var obj={a:1,b:[1,2]}

            function add(key,value){
            if(!obj[key].push){
            obj[key]=[obj[key]]
            }
            obj[key].push(value)
            }
            obj.b.push = undefined;
            add('b',3);
            console.log(obj);





            var obj={a:1,b:[1,2]}

            function add(key,value){
            if(!obj[key].push){
            obj[key]=[obj[key]]
            }
            obj[key].push(value)
            }
            obj.b.push = undefined;
            add('b',3);
            console.log(obj);





            var obj={a:1,b:[1,2]}

            function add(key,value){
            if (!Object.hasOwnProperty(key)) {
            obj[key]=;
            }
            if(!Array.isArray(obj[key])){
            obj[key]=[obj[key]]
            }
            obj[key].push(value)
            }
            add('a',3);
            add('c',4);
            console.log(obj);





            var obj={a:1,b:[1,2]}

            function add(key,value){
            if (!Object.hasOwnProperty(key)) {
            obj[key]=;
            }
            if(!Array.isArray(obj[key])){
            obj[key]=[obj[key]]
            }
            obj[key].push(value)
            }
            add('a',3);
            add('c',4);
            console.log(obj);






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 11 hours ago

























            answered Oct 3 '17 at 20:14









            Sᴀᴍ OnᴇᴌᴀSᴀᴍ Onᴇᴌᴀ

            9,90162165




            9,90162165








            • 4




              $begingroup$
              I like your answer. I don't think that one should bother with possible reassignment of push, since a) it's an absolutely cornerstone method on arrays and messing with it will lead to deadly daemons; b) the add(...) function depends on that heavily (a spread operator could be a work around instead of a push for inserts, but it's potentially much costlier, especially on large arrays). The only "real" question here is "how to reliably identify an array in JavaScript", IMO.
              $endgroup$
              – Igor Soloydenko
              Oct 3 '17 at 20:37












            • $begingroup$
              @IgorSoloydenko so is what your saying that unless you use spread syntax this is probably the best way of doing it? And if you do use spread syntax their would be a definite performance penalty?
              $endgroup$
              – qw3n
              Oct 3 '17 at 20:57










            • $begingroup$
              Yes, you read me correctly. [...someArray, newValue] will iterate over someArray's values to produce a new array. So it's by definition somewhat costlier. This may or may not be a big deal for you. Btw, I'm can't guarantee that ... is not using .push() under the hood... And I can't see any problems in what you and Sam are having in your code snippets.
              $endgroup$
              – Igor Soloydenko
              Oct 3 '17 at 21:01






            • 2




              $begingroup$
              Maybe worth mentioning: The OP's and this solution don't test whether the key exists at all. If it doesn't, it will add an undefined value to the newly created array, for example when calling add('x', 1).
              $endgroup$
              – insertusernamehere
              Oct 3 '17 at 23:03






            • 1




              $begingroup$
              yeah - I guess I have an aversion to it now because of a linter used on a project at work that complains whenever it finds calls to .hasOwnProperty() but that is simpler.
              $endgroup$
              – Sᴀᴍ Onᴇᴌᴀ
              Oct 3 '17 at 23:50
















            • 4




              $begingroup$
              I like your answer. I don't think that one should bother with possible reassignment of push, since a) it's an absolutely cornerstone method on arrays and messing with it will lead to deadly daemons; b) the add(...) function depends on that heavily (a spread operator could be a work around instead of a push for inserts, but it's potentially much costlier, especially on large arrays). The only "real" question here is "how to reliably identify an array in JavaScript", IMO.
              $endgroup$
              – Igor Soloydenko
              Oct 3 '17 at 20:37












            • $begingroup$
              @IgorSoloydenko so is what your saying that unless you use spread syntax this is probably the best way of doing it? And if you do use spread syntax their would be a definite performance penalty?
              $endgroup$
              – qw3n
              Oct 3 '17 at 20:57










            • $begingroup$
              Yes, you read me correctly. [...someArray, newValue] will iterate over someArray's values to produce a new array. So it's by definition somewhat costlier. This may or may not be a big deal for you. Btw, I'm can't guarantee that ... is not using .push() under the hood... And I can't see any problems in what you and Sam are having in your code snippets.
              $endgroup$
              – Igor Soloydenko
              Oct 3 '17 at 21:01






            • 2




              $begingroup$
              Maybe worth mentioning: The OP's and this solution don't test whether the key exists at all. If it doesn't, it will add an undefined value to the newly created array, for example when calling add('x', 1).
              $endgroup$
              – insertusernamehere
              Oct 3 '17 at 23:03






            • 1




              $begingroup$
              yeah - I guess I have an aversion to it now because of a linter used on a project at work that complains whenever it finds calls to .hasOwnProperty() but that is simpler.
              $endgroup$
              – Sᴀᴍ Onᴇᴌᴀ
              Oct 3 '17 at 23:50










            4




            4




            $begingroup$
            I like your answer. I don't think that one should bother with possible reassignment of push, since a) it's an absolutely cornerstone method on arrays and messing with it will lead to deadly daemons; b) the add(...) function depends on that heavily (a spread operator could be a work around instead of a push for inserts, but it's potentially much costlier, especially on large arrays). The only "real" question here is "how to reliably identify an array in JavaScript", IMO.
            $endgroup$
            – Igor Soloydenko
            Oct 3 '17 at 20:37






            $begingroup$
            I like your answer. I don't think that one should bother with possible reassignment of push, since a) it's an absolutely cornerstone method on arrays and messing with it will lead to deadly daemons; b) the add(...) function depends on that heavily (a spread operator could be a work around instead of a push for inserts, but it's potentially much costlier, especially on large arrays). The only "real" question here is "how to reliably identify an array in JavaScript", IMO.
            $endgroup$
            – Igor Soloydenko
            Oct 3 '17 at 20:37














            $begingroup$
            @IgorSoloydenko so is what your saying that unless you use spread syntax this is probably the best way of doing it? And if you do use spread syntax their would be a definite performance penalty?
            $endgroup$
            – qw3n
            Oct 3 '17 at 20:57




            $begingroup$
            @IgorSoloydenko so is what your saying that unless you use spread syntax this is probably the best way of doing it? And if you do use spread syntax their would be a definite performance penalty?
            $endgroup$
            – qw3n
            Oct 3 '17 at 20:57












            $begingroup$
            Yes, you read me correctly. [...someArray, newValue] will iterate over someArray's values to produce a new array. So it's by definition somewhat costlier. This may or may not be a big deal for you. Btw, I'm can't guarantee that ... is not using .push() under the hood... And I can't see any problems in what you and Sam are having in your code snippets.
            $endgroup$
            – Igor Soloydenko
            Oct 3 '17 at 21:01




            $begingroup$
            Yes, you read me correctly. [...someArray, newValue] will iterate over someArray's values to produce a new array. So it's by definition somewhat costlier. This may or may not be a big deal for you. Btw, I'm can't guarantee that ... is not using .push() under the hood... And I can't see any problems in what you and Sam are having in your code snippets.
            $endgroup$
            – Igor Soloydenko
            Oct 3 '17 at 21:01




            2




            2




            $begingroup$
            Maybe worth mentioning: The OP's and this solution don't test whether the key exists at all. If it doesn't, it will add an undefined value to the newly created array, for example when calling add('x', 1).
            $endgroup$
            – insertusernamehere
            Oct 3 '17 at 23:03




            $begingroup$
            Maybe worth mentioning: The OP's and this solution don't test whether the key exists at all. If it doesn't, it will add an undefined value to the newly created array, for example when calling add('x', 1).
            $endgroup$
            – insertusernamehere
            Oct 3 '17 at 23:03




            1




            1




            $begingroup$
            yeah - I guess I have an aversion to it now because of a linter used on a project at work that complains whenever it finds calls to .hasOwnProperty() but that is simpler.
            $endgroup$
            – Sᴀᴍ Onᴇᴌᴀ
            Oct 3 '17 at 23:50






            $begingroup$
            yeah - I guess I have an aversion to it now because of a linter used on a project at work that complains whenever it finds calls to .hasOwnProperty() but that is simpler.
            $endgroup$
            – Sᴀᴍ Onᴇᴌᴀ
            Oct 3 '17 at 23:50















            2












            $begingroup$

            Another possible way is to use concat instead of push. You may still want to do a hasOwnProperty check to ensure the property exists.



            function add(key,value) {
            if (!obj.hasOwnProperty(key)) {
            obj[key]=;
            }

            obj[key] = .concat(obj[key], value);
            }





            share|improve this answer









            $endgroup$


















              2












              $begingroup$

              Another possible way is to use concat instead of push. You may still want to do a hasOwnProperty check to ensure the property exists.



              function add(key,value) {
              if (!obj.hasOwnProperty(key)) {
              obj[key]=;
              }

              obj[key] = .concat(obj[key], value);
              }





              share|improve this answer









              $endgroup$
















                2












                2








                2





                $begingroup$

                Another possible way is to use concat instead of push. You may still want to do a hasOwnProperty check to ensure the property exists.



                function add(key,value) {
                if (!obj.hasOwnProperty(key)) {
                obj[key]=;
                }

                obj[key] = .concat(obj[key], value);
                }





                share|improve this answer









                $endgroup$



                Another possible way is to use concat instead of push. You may still want to do a hasOwnProperty check to ensure the property exists.



                function add(key,value) {
                if (!obj.hasOwnProperty(key)) {
                obj[key]=;
                }

                obj[key] = .concat(obj[key], value);
                }






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Oct 23 '17 at 18:22









                Alex.SAlex.S

                1495




                1495






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Code Review Stack Exchange!


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


                    Use MathJax to format equations. MathJax reference.


                    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%2fcodereview.stackexchange.com%2fquestions%2f177090%2fif-non-array-property-exists-convert-it-to-one-and-push-new-value%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

                    How to make a Squid Proxy server?

                    Is this a new Fibonacci Identity?

                    19世紀