在React中通过嵌套对象进行映射

huangapple go评论73阅读模式
英文:

mapping through object which is inside object in react

问题

I have roomFeature.js文件,其中有一个名为roomFeature的对象。在roomFeature中,还有一个名为beds的对象,其中包含子项"single: "1", double: "2","。

这是我所说的内容:

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

如果"sleep"可用,如何访问"1"?

我尝试过:

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

请注意,代码部分没有翻译。

英文:

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: &quot;1&quot;,
      double: &quot;3&quot;,
    },
 }
}

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

I have tried:

{roomFeatures.roomFeature.sleep.map((data) =&gt; {
 return (
  &lt;div&gt;
   &lt;span&gt;
    &lt;BsFillPersonFill /&gt;
   &lt;/span&gt;{&quot; &quot;}
    sleeps {data.single}
  &lt;/div&gt;
 );
})}

答案1

得分: 2

如果您只想访问&quot;1&quot;一次,那么您可以直接使用{roomFeatures.roomFeature.sleep.single}

如果您要循环遍历sleep对象,您应该在使用map函数之前将其转换为数组。

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

keys函数将返回对象中的键数组,因此您可以在数组上使用map函数。

英文:

If you only want to access to &quot;1&quot; 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 =&gt; {
    return (
    &lt;div&gt;
      &lt;span&gt;
        &lt;BsFillPersonFill /&gt;
      &lt;/span&gt;{&quot; &quot;}
      sleeps {temp_sleep[key]}
    &lt;/div&gt;
  );
})

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

huangapple
  • 本文由 发表于 2023年2月8日 18:24:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75384373.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定