Home > Enterprise >  cant convert undefined to object
cant convert undefined to object

Time:10-10

I have an object called usersdata whose output with JSON.stringify(usersdata) produces exactly this:

[{"ioid":"gDlMWAnLxEk8M3dKAAAF","user":"John","rank":"contributor"}]

all I want to do is get the values and wrap around html tags so I get an output like this:

<div id="gDlMWAnLxEk8M3dKAAAF">
 <span class="contributor">John</span>
</div>

so I did this:

 var udata = [];
 for (const [key, value] of Object.entries(usersdata)) {
  udata = value;
 }         
 userlist.textContent = "<div id=\"" udata[0] "\"><span class=\"" udata[1] "\">" udata[2] "</span></div>";

but I get an error that says cant convert undefined to object. Why is that?

CodePudding user response:

this way

const
  userList  = document.getElementById('user-list') 
, usersdata = [ {ioid:'gDlMWAnLxEk8M3dKAAAF', user: 'John', rank: 'contributor' } ]
  ;
userList.innerHTML = '';
for (let {ioid, user, rank} of usersdata)
  userList.innerHTML  = `<div id="${ioid}"><span class="${rank}r">${user}</span></div>\n`;

console.log('innerHTML ==>', userList.innerHTML );
console.log( JSON.stringify(usersdata) );
<div id="user-list"></div>

CodePudding user response:

In case you didn't notice, you declared udata as an array, but later on, you set udata to value, which isn't an array, and thus, you changed the type of the variable udata, which is why udata[0] doesn't work.
I assume you want to add value to the array udata, but that's not how you do it! You have to do udata.push(value).

const usersdata = [{"ioid":"gDlMWAnLxEk8M3dKAAAF","user":"John","rank":"contributor"}]
var udata = [];
 for (const [key, value] of Object.entries(usersdata)) {
  udata.push(value);
  console.log(udata)
 }   

would return

[{
  "ioid": "gDlMWAnLxEk8M3dKAAAF",
  "user": "John",
  "rank": "contributor"
}]

so now, you just have to use

userlist.textContent = "<div id=\"" udata[0].ioid "\"><span class=\"" udata[0].rank "\">" udata[0].user "</span></div>";

Here's an example with multiple user data:

const usersdata = [{"ioid":"gDlMWAnLxEk8M3dKAAAF","user":"John","rank":"contributor"},{"ioid":"gDlMWAerefd3dKAAAF","user":"Jane","rank":"editor"}];
var udata = [];
let userInfo;
const userList = document.getElementById('user-list');
 for (let [key, value] of Object.entries(usersdata)) {
  udata.push(value);
  userList.innerHTML  = "<div id=\"" udata[key].ioid "\"><span          class=\"" udata[key].rank "\">" udata[key].user "</span></div>";
  console.log("<div id=\"" udata[key].ioid "\"><span          class=\"" udata[key].rank "\">" udata[key].user "</span></div>");
 }    
 
.contributor {
   color: blue;
}
.editor {
   color: red;
}
<div id="user-list"></div>

  • Related