Convert ColdFusion Struct - assign custom key

329 views Asked by At

I am newbie in CFML language and I have a question concerning structs and arrays in ColdFusion. Notice that i am using openBD CFML server.

I have the following object(struct):

{
   "docs":{
      "23_id":{
         "content":[
            "I am"
         ]
      },
      "1_id":{
         "content":[
            "the most"
         ]
      },
      "7_id":{
         "content":[
            "crap coder"
         ]
      },
      "39_id":{
         "content":[
            "in the whole universe!"
         ]
      }
   }
}

The question: can i modify the above object to(and also retain the order if possible):

{
    "docs": [
        {
            "id": "23_id",
            "lola": "I am"
        },
        {
            "id": "1_id",
            "lola": "the most"
        },
        {
            "id": "7_id",
            "lola": "crap coder"
        },
        {
            "id": "39_id",
            "lola": "in the whole universe!"
        }
    ]
}

Notice that i need to assign custom keys (id and assign "lola" instead "content"). Are there any pointers to study in order to accomplish the above task? Any help is appreciated!

3

There are 3 answers

4
leptinella On

Do you mean that you want to take the structure and turn it into an array? If so, then yes, you can do that. However, structures don't have an inherent order so you can't retain the order. Your result may come out in the same order, but there's no particular reason why it should.

Basically you want to create a new empty array: []. Then loop over the keys inside docs (use cfloop collection="..."). For each key, append a structure to your array, so your result is an array of structures. Then insert that inside the original variable. Can't be specific without variable names.

1
Mark A Kruger On

You can definitely do what you say you want to do in the above code. You will end up with an array called doc each index of which will contain a struct with in ID key and a LOLA key. If that is what you want then your code above will work.

I'd say your data construct looks like it might benefit from something else - probably a query object. But possibly xml or json would be a good choice as well. It looks a little tortured :)

2
Marcus Fernström On

Easy, create a new array, loop your struct, and append the array as you go like so:

<cfset str = {
   "docs":{
      "23_id":{
         "content":[
            "I am"
         ]
      },
      "1_id":{
         "content":[
            "the most"
         ]
      },
      "7_id":{
         "content":[
            "crap coder"
         ]
      },
      "39_id":{
         "content":[
            "in the whole universe!"
         ]
      }
   }
}>

<cfset docs = { docs: []}>

<cfloop collection="#str.docs#" item="itm">
    <cfset arrayAppend( docs.docs, {id: itm, lola: str.docs[itm].content[1]} )>
</cfloop>

<cfdump var="#serializeJson(docs)#">