I have below code. I am able to get the values. I want to get keys. How can I get that?
var labelIndex = 0;
const labelArr = [
"Name", "IP Address", "Port", "SSH User", "SSH Port", "License"
];
const state = [
{name: "abc", ipaddr: "192.168.1.2", port: 5000},
{sshuser: "xyz", sshport: 21, license: "license.txt"}
];
{state.map((item, index1) => (
<tr key={index1}>
{Object.values(item).map((val,index2) => (
<td key={labelIndex++}>
<b>{labelArr[labelIndex]}</b><br/>
<input required
type="text"
id={labelIndex}
name={labelIndex}
onChange={(e) => {}}
value={val}/>
</td>
))}
</tr>
))}
As you can see I am using labelIndex for name and id as below.
id={labelIndex}
name={labelIndex}
I want to use corresponding key as name and id like as below.
id=ipaddr
name=ipaddr
Please let me know how I can get the key inside map().
>Solution :
To get the keys while mapping through the state array, you can use the Objet.keys method. I will share my code:
{state.map((item, index1) => (
<tr key={index1}>
{Object.keys(item).map((key, index2) => (
<td key={labelIndex++}>
<b>{labelArr[labelIndex]}</b><br/>
<input
required
type="text"
id={key}
name={key}
onChange={(e) => {}}
value={item[key]}
/>
</td>
))}
</tr>
))}
[Explanation]:
In this code, I replaced Object.values(item) (3rd line) with Object.keys(item) to iterate over the keys of each object in the state arry. The key variable inside the inner map loop now represents the key of the current property, which you can use for the id and name attributes.
Hope to be helpful for your understanding.