Friday, September 30, 2022

Add a Property to each Object in an Array of Objects with JS in LWC

 


Hi Folks, In this blog we will try to understand, How we can Add a Property to each Object in an Array of Objects with JS in LWC.

Lets suppose we have an array as given below:-

let contactData=[
                   {Name:'Rahul',Age:'31',CreditScore:750},
                   {Name:'Rogers',Age:'28',CreditScore:640}
];

Now let takes a requirement, that if the credit score is more than or equals to 700 then the rating should be 'Hot' or if it is less than the 700 rating should be 'Cold' and then add this property to every object of the Array of Objects that we have. And final output will look like as given below:

[
   {Name:'Rahul',Age:'31',CreditScore:750,rating:'Hot'},
   {Name:'Rogers',Age:'28',CreditScore:640,rating:'Cold'}
]

To achieve this we can use either forEach method or map method. 

Using forEach:

let contactData=[
                   {Name:'Rahul',Age:'31',CreditScore:750},
                   {Name:'Rogers',Age:'28',CreditScore:640}
];
contactData.forEach(element=>{
if(element.CreditScore>=700)
{ element.rating='Hot'; }
else
{
element.rating='Cold'; }
});

console.log('Final Result is:- '+JSON.stringify(contactData));

     

Using map:

let contactData=[
                   {Name:'Rahul',Age:'31',CreditScore:750},
                   {Name:'Rogers',Age:'28',CreditScore:640}
];
let finaldata=contactData.map(x=>{
if(x.CreditScore>=700)
{ return {...x,rating:'Hot'}; }
else
{
return {...x,rating:'Cold'}; }
});

console.log('Final Result is:- '+JSON.stringify(finaldata));

Output in Cosole:-

[
   {"Name":"Rahul","Age":"31","CreditScore":750,"rating":"Hot"},
   {"Name":"Rogers","Age":"28","CreditScore":640,"rating":"Cold"}
]

If you have any comments or queries about this, please feel free to mention them in the comments section below.

No comments:

Post a Comment