简体   繁体   中英

Convert JSON array of one to an object

Currently I have this:

{ 
"id": "1234"  
"elements": [
    {
      "fee": "blah",
      "fi": "blahblah",
      "fo": "blahblahblah",
      "fum": "blahblahblahblah"
    }
  ]
}

and I want to change it into this:

{ 
"id": "1234"  
"elements": {
    "fee": "blah",
    "fi": "blahblah",
    "fo": "blahblahblah",
    "fum": "blahblahblahblah"
  }
}

The JSON arrays I get only ever have one element in them so I am just trying to work out what is the best way with javascript to achieve the above?

Currently I do it this way but am curious if it's the best option.

for (var i = obj.elements.length - 1; i >= 0; i--) {
  obj.element = obj.elements[i];
}

Your code makes no sense. If there were ever two elements in the array, the second one would clobber the first.

If there really is only ever one item, you have no need at all for a loop. Just use

obj.element = obj.element[0];

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