learning to code
learning to code

Reputation: 1

mapping through object which is inside object in react

I have roomFeature.js file inside which there is object named as roomFeature. Inside roomFeature there is another object named beds with childs "single: "1", double: "2",". Here's what i am talking about:

const roomFeatures = {
 roomFeature: {
  bed: true,
  sleep: {
      single: "1",
      double: "3",
    },
 }
}

how can i access "1" if the "sleep" is available?

I have tried:

{roomFeatures.roomFeature.sleep.map((data) => {
 return (
  <div>
   <span>
    <BsFillPersonFill />
   </span>{" "}
    sleeps {data.single}
  </div>
 );
})}

Upvotes: -1

Views: 36

Answers (1)

XH栩恒
XH栩恒

Reputation: 505

If you only want to access to "1" one time then you can directly use {roomFeatures.roomFeature.sleep.single}

If you are trying to loop through the sleep object, you should convert it to an array before you use map function.

let temp_sleep = Object(roomFeatures.roomFeature.sleep);
temp_sleep.keys().map(key => {
    return (
    <div>
      <span>
        <BsFillPersonFill />
      </span>{" "}
      sleeps {temp_sleep[key]}
    </div>
  );
})

The keys function will return an array of keys in the object, so you can use the map function on the array.

Upvotes: 2

Related Questions