loading...

Mapping on the javascript objects

iamsamar profile image IamSamar ・2 min read

Yeah!! You read the tile right. Mapping on the javacsript array are simple. We can use the Map function to loop over the array. But if you want loop over the objects in js then it is quite different than the array.
consider this example

let obj = {
name:'Samar',
surname:'Deshpande',
roll_no:55
}

now if you write

obj.map((value,key)=>{
<!-- Your code goes here! -->
});

You will get an error because the map function will only work on the array and not on the objects. So there is one hack, we have to convert object into array and then loop over it. Yeah so we can do it in this way(i will be referring to react code.)

import React from "react";
import "./styles.css";

export default function App() {
  let obj = {
    name: "Samar",
    surname: "Deshpande",
    roll_no: 45
  };

  return (
    <div className="App">
      {Object.keys(obj).map((value, key) => {
        return (
          <div>
            <p>
              {value} : {obj[value]}
            </p>
          </div>
        );
      })}
    </div>
  );
}

output will be:
name : Samar
surname : Deshpande
roll_no : 45

So as you see we have used 'Object.keys(obj)'. This is ES function that will return us an array of the keys in javascript object.For More Info on Object .keys please refer 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys'.
So now Object.keys(obj) will return us an array and now we can map it over using .map function in js. But there are quite few things to keep in mind.
1) If you want to access the key of an object you use 'value'(for this example)
2) If you want to access the the value of an object use 'obj[value]' (in this case).
3) Never you map directly on objects. You will always get error

In this way you can map over the objects in Js.
If you have any suggestions you can comment here or write me at
'samdeshpande.sd@gmail.com'.

Happy Coding!!!!

Posted on by:

Discussion

markdown guide
 

You can also use Object.entries to avoid the lookup on obj. So, to map over an object, you have this:

Object.entries(obj).map(([key, value]) => (
    `${key} = ${value}`;
));