Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

better way push array of an object to array of an object based on the same id?

hi I want to push array of an object to array of an object so the the new property will push to the array of object based on the same _id
this is the original data :

const data =[
             { 
              foo:foo1,
              data:{
                   _id:"a1",
                   man:2
                  }
            },
            { 
              foo:foo1,
              data:{
                   _id:"a1",
                   man:2
                }
             }
           ]

this is the data that I want to put on my original data

const d = [{
             _id:"a1",
             women:4,
           }]

And the desired output is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

      const data =[
             { 
              foo:foo1,
              data:{
                   _id:"a1",
                   man:2,
                   women:4
                  }
            },
            { 
              foo:foo1,
              data:{
                   _id:"a1",
                   man:2,
                   women:4
                }
             }
           ]

I think it can be done using for loop and check if the _id is the same and push it to the object, but is there any better way? or using lodash? any idea? thanks in advance

>Solution :

You can try this!

const d = [{
             _id:"a1",
             women:4,
           }
           ]
    
const data =[
             { 
              foo:"foo1",
              data:{
                   _id:"a1",
                   man:2
                  }
            },
            { 
              foo:"foo1",
              data:{
                   _id:"a1",
                   man:2
                }
             }
           ]    
var arr = data.map(function(obj, i){
    d.map(function(o,i){
    if(obj.data._id == o._id)
    {
        obj.data.women = o.women;
    }
    });
    return obj;
});

console.log(arr);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading