tshoemake
tshoemake

Reputation: 1351

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:

enter image description here

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: enter image description here

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

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

Upvotes: 2

Views: 89

Answers (2)

mooga
mooga

Reputation: 3297

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)

Upvotes: 1

HMR
HMR

Reputation: 39250

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.

Upvotes: 3

Related Questions