Sathya Sathya - 1 month ago 8
jQuery Question

How to insert objects through javascript?

I have stored group of objects into one array called 'resData' and i'm having one more array of data called 'approvedIds', there have included all approved id's. Here i want to match these two arrays and add one new key into 'resData' array like 'approveStatus:"approve"'. How to do this one in javascript?

All data's,

var resData = [
{
firstName:"Jhon",
lastName:"adam",
emailId:"jhn12@gmail.com",
id:"01"
},
{
firstName:"Kyle",
lastName:"Miller",
emailId:"kl12@gmail.com",
id:"02"
},
{
firstName:"Jhonathan",
lastName:"adam",
emailId:"jadm12@gmail.com",
id:"03"
},
{
firstName:"Lewis",
lastName:"harber",
emailId:"lewh12@gmail.com",
id:"04"
}
];


Approved id's array,

var approvedIds = ['01', '03'];


My output will be like this,

var resData = [
{
firstName:"Jhon",
lastName:"adam",
emailId:"jhn12@gmail.com",
id:"01",
approveStatus:'approved'
},
{
firstName:"Kyle",
lastName:"Miller",
emailId:"kl12@gmail.com",
id:"02"
},
{
firstName:"Jhonathan",
lastName:"adam",
emailId:"jadm12@gmail.com",
id:"03",
approveStatus:'approved'
},
{
firstName:"Lewis",
lastName:"harber",
emailId:"lewh12@gmail.com",
id:"04"
}
];

Answer

You can try this. Use forEach and indexOf functions

var resData = [
    {
        firstName:"Jhon",
        lastName:"adam",
        emailId:"jhn12@gmail.com",
        id:"01"
    },
    {
        firstName:"Kyle",
        lastName:"Miller",
        emailId:"kl12@gmail.com",
        id:"02"
    },
    {
        firstName:"Jhonathan",
        lastName:"adam",
        emailId:"jadm12@gmail.com",
        id:"03"
    },
    {
        firstName:"Lewis",
        lastName:"harber",
        emailId:"lewh12@gmail.com",
        id:"04"
    }
];


var approvedIds = ['01', '03'];

resData.forEach(item => {
  if(approvedIds.indexOf(item.id) !== -1){
       item.approvedStatus = 'approved';
    }
} );

console.log(resData);

Comments