Posts

Showing posts with the label Array of objects

Add key-value pair to every object in array of objects in JavaScript

Image
Sometimes, we've to add flag or some new key-value pair to every object in array of objects. For that we can follow three ways to achieve it. For suppose, we have an array of objects as below and we want to add gender key to all the objects     students  = [     {        name:   'Radhika' ,        age:   26 ,     },     {        name:   'Radha' ,        age:   24 ,     },     {        name:   'Jyothi' ,        age:   25 ,     },   ]; // Expected Output    students  = [     {        name:   'Radhika' ,        age:   ...

Extract list of values from an array of objects to an array based on a key in JavaScript.

Image
There may be a situation where you want to extract the list of values of a specific key from an objects to an array.  Method 1: In one way, we can use both for loop and Array.push() method and achieve it.  For example, we have an Array of objects as below let studentsObject = [     {         "name" : "John" ,         "age" : 26     },     {         "name" : "Helen" ,         "age" : 42     },     {         "name" : "Cole" ,         "age" : 54     },     {         "name" : "Noah" ,         "age" : 38     } ] we can extract the values as shown below  let namesList ; studentsObject . forEach ( student => {     namesList . push ( student . name ) }); console . log ( namesList ); //Output [ 'John' , 'Helen' , 'Cole'...