Nathan30
Nathan30

Reputation: 899

JAVASCRIPT object to array conversion

I search on stackoverflow before post my question, but I didn't find any solution. I have an object like this :

"{"COURRIERS":
     {"05. Juridique":
         [{"res_id":100,"type_label":"Plainte","subject":"test23","doctypes_first_level_label":"COURRIERS","doctypes_second_level_label":"05. Juridique","folder_level":2}]
     }
}"

And I need to access it like an array, in order to get the information like res_id etc..

How can I do this ?

Thanks in advance

Upvotes: 0

Views: 65

Answers (3)

larz
larz

Reputation: 5766

Assuming that you won't have more than one object/array in each layer, this should get you what you need.

let obj = {
  "COURRIERS": {
    "05. Juridique": [{
      "res_id": 100,
      "type_label": "Plainte",
      "subject": "test23",
      "doctypes_first_level_label": "COURRIERS",
      "doctypes_second_level_label": "05. Juridique",
      "folder_level": 2
    }]
  }
}

let folder = Object.keys(obj)[0]
let type = Object.keys(obj[folder])[0]
let result = obj[folder][type][0]

console.log(result)

Upvotes: 2

6be709c0
6be709c0

Reputation: 8461

Something like that ?

(I insert the data inside a variable and print the wanted result with key index)

let obj = {
   "COURRIERS":{
      "05. Juridique":[
         {
            "res_id":100,
            "type_label":"Plainte",
            "subject":"test23",
            "doctypes_first_level_label":"COURRIERS",
            "doctypes_second_level_label":"05. Juridique",
            "folder_level":2
         }
      ]
   }
};

console.log(obj["COURRIERS"]["05. Juridique"][0]["res_id"]);

EDIT

You want to acess it with variable. For avoid bug, I strong recommend you to check if the variable value key exist in the array/object like :

let folder = 'COURRIERS';

if(folder.indexOf(data) >= 0) { // folder.indexOf(data) = 0
// ... finish the job here :)
}
// indexOf return -1 if the value is not found

Upvotes: 1

hafridi
hafridi

Reputation: 278

You can gain access to the data in multiple ways. The following below will help clarify some of the way you can access some of the data.

myObj.type              = "Dot syntax";
myObj.type              = "Dot syntax";
myObj["date created"]   = "String with space";
myObj[str]              = "String value";
myObj[rand]             = "Random Number";
myObj[obj]              = "Object";
myObj[""]               = "Even an empty string";

For your problem you can use the following

var x = { 
 "COURRIERS":{
  "05. Juridique":[
     {
        "res_id":100,
        "type_label":"Plainte",
        "subject":"test23",
        "doctypes_first_level_label":"COURRIERS",
        "doctypes_second_level_label":"05. Juridique",
        "folder_level":2
     }
  ]
}};
console.log(x['COURRIERS']['05. Juridique'][0].res_id)

Upvotes: 1

Related Questions