add an object to an array if it doesn't have the same key with one of the objects in the array











up vote
0
down vote

favorite












I'm using Lodash. I have the array below:



const array = [{id:1,name:a},{id:2,name:b},{id:3,name:c},{id:4,name:d},{id:5,name:e}];


and I'm about to add another object to this array but before that, I need to check if the new object's name is already in the array or not and if there is one with the name I won't add the new object anymore.
I know some ways to do it, for instance, a loop with _.map, but want to make sure if there is an easier way.










share|improve this question


























    up vote
    0
    down vote

    favorite












    I'm using Lodash. I have the array below:



    const array = [{id:1,name:a},{id:2,name:b},{id:3,name:c},{id:4,name:d},{id:5,name:e}];


    and I'm about to add another object to this array but before that, I need to check if the new object's name is already in the array or not and if there is one with the name I won't add the new object anymore.
    I know some ways to do it, for instance, a loop with _.map, but want to make sure if there is an easier way.










    share|improve this question
























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I'm using Lodash. I have the array below:



      const array = [{id:1,name:a},{id:2,name:b},{id:3,name:c},{id:4,name:d},{id:5,name:e}];


      and I'm about to add another object to this array but before that, I need to check if the new object's name is already in the array or not and if there is one with the name I won't add the new object anymore.
      I know some ways to do it, for instance, a loop with _.map, but want to make sure if there is an easier way.










      share|improve this question













      I'm using Lodash. I have the array below:



      const array = [{id:1,name:a},{id:2,name:b},{id:3,name:c},{id:4,name:d},{id:5,name:e}];


      and I'm about to add another object to this array but before that, I need to check if the new object's name is already in the array or not and if there is one with the name I won't add the new object anymore.
      I know some ways to do it, for instance, a loop with _.map, but want to make sure if there is an easier way.







      javascript lodash






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 22 at 16:27









      farm command

      6518




      6518
























          4 Answers
          4






          active

          oldest

          votes

















          up vote
          2
          down vote



          accepted










          You could use Lodash's some which if provided with an appropriate predicate e.g. (item => item.name === newName) will return a boolean indicating whether or not the item already exists (in this case, true would mean the name already exists). The benefit of using this over other iterating methods is that it will stop as soon as it finds one that returns true resulting in better performance.






          share|improve this answer




























            up vote
            0
            down vote













            With native javascript , you can use findIndex, this will return the index of the object where the name matches. If it returns -1 then there is no such object with same name. In that case update the array.






            const array = [{
            id: 1,
            name: 'a'
            }, {
            id: 2,
            name: 'b'
            }, {
            id: 3,
            name: 'c'
            }, {
            id: 4,
            name: 'd'
            }, {
            id: 5,
            name: 'e'
            }];

            let newObjToAdd = {
            id: 1,
            name: 'z'
            };
            let newObjNotToAdd = {
            id: 1,
            name: 'a'
            }


            function updateArray(obj) {
            let k = array.findIndex((item) => {
            return item.name === obj.name;
            })
            if (k === -1) {
            array.push(obj)
            } else {
            console.log('Array contains object with this name')
            }
            }

            updateArray(newObjToAdd);
            console.log(array)
            updateArray(newObjNotToAdd);








            share|improve this answer





















            • thanks, that is nice but i needed to do it via Lodash, but thanks anyway
              – farm command
              Nov 22 at 16:49






            • 1




              if you can use loadash you can use js also
              – brk
              Nov 22 at 16:50










            • i know that, but lodash makes it shorter and easier to document
              – farm command
              Nov 22 at 17:04


















            up vote
            0
            down vote













            You don't need lodash for some. You get that with native JS too (ES6):






            const array = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'},{id:4,name:'d'},{id:5,name:'e'}];

            console.log(array.some(e => e.name === 'a'));

            if (!array.some(e => e.name === 'z')) {
            array.push({id: 5, name: 'z'});
            }

            console.log(array);








            share|improve this answer




























              up vote
              0
              down vote













              Doing this with lodash is few chars shorter but here is how you could do it with ES6 and Array.some:






              const array = [{ id: 1, name: "A" }, { id: 2, name: "B" }, { id: 3, name: "C" }, { id: 4, name: "D" }, { id: 5, name: "C" }];

              const maybeUpdate = (arr, obj) => {
              if(!array.some(x => x.id == obj.id))
              array.push(obj)
              }

              maybeUpdate(array, {id: 2, name: "F"}) // id exists wont insert
              maybeUpdate(array, {id: 12, name: "F"}) // will insert

              console.log(array)





              Same idea with lodash and _.some would be:






              const array = [{ id: 1, name: "A" }, { id: 2, name: "B" }, { id: 3, name: "C" }, { id: 4, name: "D" }, { id: 5, name: "C" }];

              const maybeUpdate = (arr, obj) => {
              if(!_.some(array, {id: obj.id}))
              array.push(obj)
              }

              maybeUpdate(array, {id: 2, name: "F"}) // id exists wont insert
              maybeUpdate(array, {id: 12, name: "F"}) // will insert

              console.log(array)

              <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>





              Note that you could also use various other ways to get the same result. Array.find or _.find would work as well since all you have to do is to check if there was a hit:



              const maybeUpdate = (arr, obj) => {
              if(!_.find(array, {id: obj.id})) // or if(!array.find(x => x.id == obj.id))
              array.push(obj)
              }





              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%2f53435009%2fadd-an-object-to-an-array-if-it-doesnt-have-the-same-key-with-one-of-the-object%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                4 Answers
                4






                active

                oldest

                votes








                4 Answers
                4






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes








                up vote
                2
                down vote



                accepted










                You could use Lodash's some which if provided with an appropriate predicate e.g. (item => item.name === newName) will return a boolean indicating whether or not the item already exists (in this case, true would mean the name already exists). The benefit of using this over other iterating methods is that it will stop as soon as it finds one that returns true resulting in better performance.






                share|improve this answer

























                  up vote
                  2
                  down vote



                  accepted










                  You could use Lodash's some which if provided with an appropriate predicate e.g. (item => item.name === newName) will return a boolean indicating whether or not the item already exists (in this case, true would mean the name already exists). The benefit of using this over other iterating methods is that it will stop as soon as it finds one that returns true resulting in better performance.






                  share|improve this answer























                    up vote
                    2
                    down vote



                    accepted







                    up vote
                    2
                    down vote



                    accepted






                    You could use Lodash's some which if provided with an appropriate predicate e.g. (item => item.name === newName) will return a boolean indicating whether or not the item already exists (in this case, true would mean the name already exists). The benefit of using this over other iterating methods is that it will stop as soon as it finds one that returns true resulting in better performance.






                    share|improve this answer












                    You could use Lodash's some which if provided with an appropriate predicate e.g. (item => item.name === newName) will return a boolean indicating whether or not the item already exists (in this case, true would mean the name already exists). The benefit of using this over other iterating methods is that it will stop as soon as it finds one that returns true resulting in better performance.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 22 at 16:32









                    jordrake

                    28914




                    28914
























                        up vote
                        0
                        down vote













                        With native javascript , you can use findIndex, this will return the index of the object where the name matches. If it returns -1 then there is no such object with same name. In that case update the array.






                        const array = [{
                        id: 1,
                        name: 'a'
                        }, {
                        id: 2,
                        name: 'b'
                        }, {
                        id: 3,
                        name: 'c'
                        }, {
                        id: 4,
                        name: 'd'
                        }, {
                        id: 5,
                        name: 'e'
                        }];

                        let newObjToAdd = {
                        id: 1,
                        name: 'z'
                        };
                        let newObjNotToAdd = {
                        id: 1,
                        name: 'a'
                        }


                        function updateArray(obj) {
                        let k = array.findIndex((item) => {
                        return item.name === obj.name;
                        })
                        if (k === -1) {
                        array.push(obj)
                        } else {
                        console.log('Array contains object with this name')
                        }
                        }

                        updateArray(newObjToAdd);
                        console.log(array)
                        updateArray(newObjNotToAdd);








                        share|improve this answer





















                        • thanks, that is nice but i needed to do it via Lodash, but thanks anyway
                          – farm command
                          Nov 22 at 16:49






                        • 1




                          if you can use loadash you can use js also
                          – brk
                          Nov 22 at 16:50










                        • i know that, but lodash makes it shorter and easier to document
                          – farm command
                          Nov 22 at 17:04















                        up vote
                        0
                        down vote













                        With native javascript , you can use findIndex, this will return the index of the object where the name matches. If it returns -1 then there is no such object with same name. In that case update the array.






                        const array = [{
                        id: 1,
                        name: 'a'
                        }, {
                        id: 2,
                        name: 'b'
                        }, {
                        id: 3,
                        name: 'c'
                        }, {
                        id: 4,
                        name: 'd'
                        }, {
                        id: 5,
                        name: 'e'
                        }];

                        let newObjToAdd = {
                        id: 1,
                        name: 'z'
                        };
                        let newObjNotToAdd = {
                        id: 1,
                        name: 'a'
                        }


                        function updateArray(obj) {
                        let k = array.findIndex((item) => {
                        return item.name === obj.name;
                        })
                        if (k === -1) {
                        array.push(obj)
                        } else {
                        console.log('Array contains object with this name')
                        }
                        }

                        updateArray(newObjToAdd);
                        console.log(array)
                        updateArray(newObjNotToAdd);








                        share|improve this answer





















                        • thanks, that is nice but i needed to do it via Lodash, but thanks anyway
                          – farm command
                          Nov 22 at 16:49






                        • 1




                          if you can use loadash you can use js also
                          – brk
                          Nov 22 at 16:50










                        • i know that, but lodash makes it shorter and easier to document
                          – farm command
                          Nov 22 at 17:04













                        up vote
                        0
                        down vote










                        up vote
                        0
                        down vote









                        With native javascript , you can use findIndex, this will return the index of the object where the name matches. If it returns -1 then there is no such object with same name. In that case update the array.






                        const array = [{
                        id: 1,
                        name: 'a'
                        }, {
                        id: 2,
                        name: 'b'
                        }, {
                        id: 3,
                        name: 'c'
                        }, {
                        id: 4,
                        name: 'd'
                        }, {
                        id: 5,
                        name: 'e'
                        }];

                        let newObjToAdd = {
                        id: 1,
                        name: 'z'
                        };
                        let newObjNotToAdd = {
                        id: 1,
                        name: 'a'
                        }


                        function updateArray(obj) {
                        let k = array.findIndex((item) => {
                        return item.name === obj.name;
                        })
                        if (k === -1) {
                        array.push(obj)
                        } else {
                        console.log('Array contains object with this name')
                        }
                        }

                        updateArray(newObjToAdd);
                        console.log(array)
                        updateArray(newObjNotToAdd);








                        share|improve this answer












                        With native javascript , you can use findIndex, this will return the index of the object where the name matches. If it returns -1 then there is no such object with same name. In that case update the array.






                        const array = [{
                        id: 1,
                        name: 'a'
                        }, {
                        id: 2,
                        name: 'b'
                        }, {
                        id: 3,
                        name: 'c'
                        }, {
                        id: 4,
                        name: 'd'
                        }, {
                        id: 5,
                        name: 'e'
                        }];

                        let newObjToAdd = {
                        id: 1,
                        name: 'z'
                        };
                        let newObjNotToAdd = {
                        id: 1,
                        name: 'a'
                        }


                        function updateArray(obj) {
                        let k = array.findIndex((item) => {
                        return item.name === obj.name;
                        })
                        if (k === -1) {
                        array.push(obj)
                        } else {
                        console.log('Array contains object with this name')
                        }
                        }

                        updateArray(newObjToAdd);
                        console.log(array)
                        updateArray(newObjNotToAdd);








                        const array = [{
                        id: 1,
                        name: 'a'
                        }, {
                        id: 2,
                        name: 'b'
                        }, {
                        id: 3,
                        name: 'c'
                        }, {
                        id: 4,
                        name: 'd'
                        }, {
                        id: 5,
                        name: 'e'
                        }];

                        let newObjToAdd = {
                        id: 1,
                        name: 'z'
                        };
                        let newObjNotToAdd = {
                        id: 1,
                        name: 'a'
                        }


                        function updateArray(obj) {
                        let k = array.findIndex((item) => {
                        return item.name === obj.name;
                        })
                        if (k === -1) {
                        array.push(obj)
                        } else {
                        console.log('Array contains object with this name')
                        }
                        }

                        updateArray(newObjToAdd);
                        console.log(array)
                        updateArray(newObjNotToAdd);





                        const array = [{
                        id: 1,
                        name: 'a'
                        }, {
                        id: 2,
                        name: 'b'
                        }, {
                        id: 3,
                        name: 'c'
                        }, {
                        id: 4,
                        name: 'd'
                        }, {
                        id: 5,
                        name: 'e'
                        }];

                        let newObjToAdd = {
                        id: 1,
                        name: 'z'
                        };
                        let newObjNotToAdd = {
                        id: 1,
                        name: 'a'
                        }


                        function updateArray(obj) {
                        let k = array.findIndex((item) => {
                        return item.name === obj.name;
                        })
                        if (k === -1) {
                        array.push(obj)
                        } else {
                        console.log('Array contains object with this name')
                        }
                        }

                        updateArray(newObjToAdd);
                        console.log(array)
                        updateArray(newObjNotToAdd);






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Nov 22 at 16:33









                        brk

                        25.2k31939




                        25.2k31939












                        • thanks, that is nice but i needed to do it via Lodash, but thanks anyway
                          – farm command
                          Nov 22 at 16:49






                        • 1




                          if you can use loadash you can use js also
                          – brk
                          Nov 22 at 16:50










                        • i know that, but lodash makes it shorter and easier to document
                          – farm command
                          Nov 22 at 17:04


















                        • thanks, that is nice but i needed to do it via Lodash, but thanks anyway
                          – farm command
                          Nov 22 at 16:49






                        • 1




                          if you can use loadash you can use js also
                          – brk
                          Nov 22 at 16:50










                        • i know that, but lodash makes it shorter and easier to document
                          – farm command
                          Nov 22 at 17:04
















                        thanks, that is nice but i needed to do it via Lodash, but thanks anyway
                        – farm command
                        Nov 22 at 16:49




                        thanks, that is nice but i needed to do it via Lodash, but thanks anyway
                        – farm command
                        Nov 22 at 16:49




                        1




                        1




                        if you can use loadash you can use js also
                        – brk
                        Nov 22 at 16:50




                        if you can use loadash you can use js also
                        – brk
                        Nov 22 at 16:50












                        i know that, but lodash makes it shorter and easier to document
                        – farm command
                        Nov 22 at 17:04




                        i know that, but lodash makes it shorter and easier to document
                        – farm command
                        Nov 22 at 17:04










                        up vote
                        0
                        down vote













                        You don't need lodash for some. You get that with native JS too (ES6):






                        const array = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'},{id:4,name:'d'},{id:5,name:'e'}];

                        console.log(array.some(e => e.name === 'a'));

                        if (!array.some(e => e.name === 'z')) {
                        array.push({id: 5, name: 'z'});
                        }

                        console.log(array);








                        share|improve this answer

























                          up vote
                          0
                          down vote













                          You don't need lodash for some. You get that with native JS too (ES6):






                          const array = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'},{id:4,name:'d'},{id:5,name:'e'}];

                          console.log(array.some(e => e.name === 'a'));

                          if (!array.some(e => e.name === 'z')) {
                          array.push({id: 5, name: 'z'});
                          }

                          console.log(array);








                          share|improve this answer























                            up vote
                            0
                            down vote










                            up vote
                            0
                            down vote









                            You don't need lodash for some. You get that with native JS too (ES6):






                            const array = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'},{id:4,name:'d'},{id:5,name:'e'}];

                            console.log(array.some(e => e.name === 'a'));

                            if (!array.some(e => e.name === 'z')) {
                            array.push({id: 5, name: 'z'});
                            }

                            console.log(array);








                            share|improve this answer












                            You don't need lodash for some. You get that with native JS too (ES6):






                            const array = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'},{id:4,name:'d'},{id:5,name:'e'}];

                            console.log(array.some(e => e.name === 'a'));

                            if (!array.some(e => e.name === 'z')) {
                            array.push({id: 5, name: 'z'});
                            }

                            console.log(array);








                            const array = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'},{id:4,name:'d'},{id:5,name:'e'}];

                            console.log(array.some(e => e.name === 'a'));

                            if (!array.some(e => e.name === 'z')) {
                            array.push({id: 5, name: 'z'});
                            }

                            console.log(array);





                            const array = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'},{id:4,name:'d'},{id:5,name:'e'}];

                            console.log(array.some(e => e.name === 'a'));

                            if (!array.some(e => e.name === 'z')) {
                            array.push({id: 5, name: 'z'});
                            }

                            console.log(array);






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 22 at 17:04









                            slider

                            7,8651129




                            7,8651129






















                                up vote
                                0
                                down vote













                                Doing this with lodash is few chars shorter but here is how you could do it with ES6 and Array.some:






                                const array = [{ id: 1, name: "A" }, { id: 2, name: "B" }, { id: 3, name: "C" }, { id: 4, name: "D" }, { id: 5, name: "C" }];

                                const maybeUpdate = (arr, obj) => {
                                if(!array.some(x => x.id == obj.id))
                                array.push(obj)
                                }

                                maybeUpdate(array, {id: 2, name: "F"}) // id exists wont insert
                                maybeUpdate(array, {id: 12, name: "F"}) // will insert

                                console.log(array)





                                Same idea with lodash and _.some would be:






                                const array = [{ id: 1, name: "A" }, { id: 2, name: "B" }, { id: 3, name: "C" }, { id: 4, name: "D" }, { id: 5, name: "C" }];

                                const maybeUpdate = (arr, obj) => {
                                if(!_.some(array, {id: obj.id}))
                                array.push(obj)
                                }

                                maybeUpdate(array, {id: 2, name: "F"}) // id exists wont insert
                                maybeUpdate(array, {id: 12, name: "F"}) // will insert

                                console.log(array)

                                <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>





                                Note that you could also use various other ways to get the same result. Array.find or _.find would work as well since all you have to do is to check if there was a hit:



                                const maybeUpdate = (arr, obj) => {
                                if(!_.find(array, {id: obj.id})) // or if(!array.find(x => x.id == obj.id))
                                array.push(obj)
                                }





                                share|improve this answer



























                                  up vote
                                  0
                                  down vote













                                  Doing this with lodash is few chars shorter but here is how you could do it with ES6 and Array.some:






                                  const array = [{ id: 1, name: "A" }, { id: 2, name: "B" }, { id: 3, name: "C" }, { id: 4, name: "D" }, { id: 5, name: "C" }];

                                  const maybeUpdate = (arr, obj) => {
                                  if(!array.some(x => x.id == obj.id))
                                  array.push(obj)
                                  }

                                  maybeUpdate(array, {id: 2, name: "F"}) // id exists wont insert
                                  maybeUpdate(array, {id: 12, name: "F"}) // will insert

                                  console.log(array)





                                  Same idea with lodash and _.some would be:






                                  const array = [{ id: 1, name: "A" }, { id: 2, name: "B" }, { id: 3, name: "C" }, { id: 4, name: "D" }, { id: 5, name: "C" }];

                                  const maybeUpdate = (arr, obj) => {
                                  if(!_.some(array, {id: obj.id}))
                                  array.push(obj)
                                  }

                                  maybeUpdate(array, {id: 2, name: "F"}) // id exists wont insert
                                  maybeUpdate(array, {id: 12, name: "F"}) // will insert

                                  console.log(array)

                                  <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>





                                  Note that you could also use various other ways to get the same result. Array.find or _.find would work as well since all you have to do is to check if there was a hit:



                                  const maybeUpdate = (arr, obj) => {
                                  if(!_.find(array, {id: obj.id})) // or if(!array.find(x => x.id == obj.id))
                                  array.push(obj)
                                  }





                                  share|improve this answer

























                                    up vote
                                    0
                                    down vote










                                    up vote
                                    0
                                    down vote









                                    Doing this with lodash is few chars shorter but here is how you could do it with ES6 and Array.some:






                                    const array = [{ id: 1, name: "A" }, { id: 2, name: "B" }, { id: 3, name: "C" }, { id: 4, name: "D" }, { id: 5, name: "C" }];

                                    const maybeUpdate = (arr, obj) => {
                                    if(!array.some(x => x.id == obj.id))
                                    array.push(obj)
                                    }

                                    maybeUpdate(array, {id: 2, name: "F"}) // id exists wont insert
                                    maybeUpdate(array, {id: 12, name: "F"}) // will insert

                                    console.log(array)





                                    Same idea with lodash and _.some would be:






                                    const array = [{ id: 1, name: "A" }, { id: 2, name: "B" }, { id: 3, name: "C" }, { id: 4, name: "D" }, { id: 5, name: "C" }];

                                    const maybeUpdate = (arr, obj) => {
                                    if(!_.some(array, {id: obj.id}))
                                    array.push(obj)
                                    }

                                    maybeUpdate(array, {id: 2, name: "F"}) // id exists wont insert
                                    maybeUpdate(array, {id: 12, name: "F"}) // will insert

                                    console.log(array)

                                    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>





                                    Note that you could also use various other ways to get the same result. Array.find or _.find would work as well since all you have to do is to check if there was a hit:



                                    const maybeUpdate = (arr, obj) => {
                                    if(!_.find(array, {id: obj.id})) // or if(!array.find(x => x.id == obj.id))
                                    array.push(obj)
                                    }





                                    share|improve this answer














                                    Doing this with lodash is few chars shorter but here is how you could do it with ES6 and Array.some:






                                    const array = [{ id: 1, name: "A" }, { id: 2, name: "B" }, { id: 3, name: "C" }, { id: 4, name: "D" }, { id: 5, name: "C" }];

                                    const maybeUpdate = (arr, obj) => {
                                    if(!array.some(x => x.id == obj.id))
                                    array.push(obj)
                                    }

                                    maybeUpdate(array, {id: 2, name: "F"}) // id exists wont insert
                                    maybeUpdate(array, {id: 12, name: "F"}) // will insert

                                    console.log(array)





                                    Same idea with lodash and _.some would be:






                                    const array = [{ id: 1, name: "A" }, { id: 2, name: "B" }, { id: 3, name: "C" }, { id: 4, name: "D" }, { id: 5, name: "C" }];

                                    const maybeUpdate = (arr, obj) => {
                                    if(!_.some(array, {id: obj.id}))
                                    array.push(obj)
                                    }

                                    maybeUpdate(array, {id: 2, name: "F"}) // id exists wont insert
                                    maybeUpdate(array, {id: 12, name: "F"}) // will insert

                                    console.log(array)

                                    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>





                                    Note that you could also use various other ways to get the same result. Array.find or _.find would work as well since all you have to do is to check if there was a hit:



                                    const maybeUpdate = (arr, obj) => {
                                    if(!_.find(array, {id: obj.id})) // or if(!array.find(x => x.id == obj.id))
                                    array.push(obj)
                                    }





                                    const array = [{ id: 1, name: "A" }, { id: 2, name: "B" }, { id: 3, name: "C" }, { id: 4, name: "D" }, { id: 5, name: "C" }];

                                    const maybeUpdate = (arr, obj) => {
                                    if(!array.some(x => x.id == obj.id))
                                    array.push(obj)
                                    }

                                    maybeUpdate(array, {id: 2, name: "F"}) // id exists wont insert
                                    maybeUpdate(array, {id: 12, name: "F"}) // will insert

                                    console.log(array)





                                    const array = [{ id: 1, name: "A" }, { id: 2, name: "B" }, { id: 3, name: "C" }, { id: 4, name: "D" }, { id: 5, name: "C" }];

                                    const maybeUpdate = (arr, obj) => {
                                    if(!array.some(x => x.id == obj.id))
                                    array.push(obj)
                                    }

                                    maybeUpdate(array, {id: 2, name: "F"}) // id exists wont insert
                                    maybeUpdate(array, {id: 12, name: "F"}) // will insert

                                    console.log(array)





                                    const array = [{ id: 1, name: "A" }, { id: 2, name: "B" }, { id: 3, name: "C" }, { id: 4, name: "D" }, { id: 5, name: "C" }];

                                    const maybeUpdate = (arr, obj) => {
                                    if(!_.some(array, {id: obj.id}))
                                    array.push(obj)
                                    }

                                    maybeUpdate(array, {id: 2, name: "F"}) // id exists wont insert
                                    maybeUpdate(array, {id: 12, name: "F"}) // will insert

                                    console.log(array)

                                    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>





                                    const array = [{ id: 1, name: "A" }, { id: 2, name: "B" }, { id: 3, name: "C" }, { id: 4, name: "D" }, { id: 5, name: "C" }];

                                    const maybeUpdate = (arr, obj) => {
                                    if(!_.some(array, {id: obj.id}))
                                    array.push(obj)
                                    }

                                    maybeUpdate(array, {id: 2, name: "F"}) // id exists wont insert
                                    maybeUpdate(array, {id: 12, name: "F"}) // will insert

                                    console.log(array)

                                    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>






                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Nov 22 at 17:11

























                                    answered Nov 22 at 17:05









                                    Akrion

                                    9,11911223




                                    9,11911223






























                                        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%2f53435009%2fadd-an-object-to-an-array-if-it-doesnt-have-the-same-key-with-one-of-the-object%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

                                        What visual should I use to simply compare current year value vs last year in Power BI desktop

                                        How to ignore python UserWarning in pytest?

                                        Alexandru Averescu