Friday, March 10, 2023

Listing / Getting Keys Values etc from javascript objects

https://www.educative.io/answers/how-to-get-keys-values-and-entries-in-javascript-object

If we don't know what a javascript object contains, we can use these to learn more about the object - 

    Object.keys(obj) – returns all the keys of object as array
    Object.values(obj) – returns all the values of the object as array
    Object.entries(obj) – returns an array of [key, value]

and we can check the length of the object using Object.keys(obj).length

using which we can loop through the object, or we can use foreach or for var in array and so on.

messages.forEach(function(message) {
   console.log(message);
}

for(let message of messages){
   console.log(message);
}

for(let key in messages){
       console.log(messages[key]);
 }

data.messages.forEach((obj, i) => {
     console.log("msgFrom", obj.msgFrom);
     console.log("msgBody", obj.msgBody);
 });

data.messages.map((obj, i) => {
     console.log("msgFrom", obj.msgFrom);
     console.log("msgBody", obj.msgBody);
 });

We can also implement lookup tables using objects,

https://www.educative.io/answers/how-to-use-objects-for-lookup-in-javascript




No comments:

Post a Comment