简体   繁体   中英

JavaScript converting an object to an array

I've researched for about a day and haven't had any luck. I'm trying to access the object properties to simply add it to a typed class in JavaScript. How can i accomplish this? This is the object im receiving:

在此处输入图片说明

And this my code resulting in the following error:

Object.keys(selected).forEach(function (key) {
        console.log(selected[key]);
    });

Error:

ERROR TypeError: Cannot convert undefined or null to object

Any help is most appreciated as I've come to here as a last resort.

selected looks like this: 在此处输入图片说明

Object.keys(selected)... the selected in json string:

{
 "selected": [
    {
      "Id": 4,
      "Type": 0,
      "Image": "",
      "Name": "TestName",
      "Roles": "TestRole",
      "Facility": "TestFacil"
    }
  ]
}

The variable selected is an array, you can try this:

selected.forEach(
  item=>
    Object.keys(item).forEach(function (key) {
      console.log(item[key]);
    })
)

It could also be:

selected.selected.forEach(

In your question it's not clear what the name is of the value you are logging the json string of.

 let data = { "selected": [ { "Id": 4, "Type": 0, "Image": "", "Name": "TestName", "Roles": "TestRole", "Facility": "TestFacil" } ] } let arr = []; for (var key in data) { arr.push(data[key]); } console.log(arr) 

or you can use that if you wanna convert the whole object to arrays of arrays

  let data = { "selected": [ { "Id": 4, "Type": 0, "Image": "", "Name": "TestName", "Roles": "TestRole", "Facility": "TestFacil" } ] } var arr = []; var i =0; for( var key in data){ var innerArr = [key]; arr.push(innerArr) for(var values in data[key]){ for(var keys in data[key][values]){ var innerArr3 = [keys]; innerArr.push(innerArr3) innerArr3.push(data[key][values][keys]) } } } console.log(arr) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM