0

I'd like to sort objects by prop name, eg

const a = {
    method: "GET",
    url: "asd",
    headers: {
        Content: "application/json",
        Authorization: "token",
    },
}

then select only the object in the buffer, apply our function, and it would turn into

const a = {
    headers: {
        Authorization: "token",
        Content: "application/json",
    },
    method: "GET",
    url: "asd",
}

I know there's a sort-regexp-fields

2

If your JavaScript code happened to also be valid JSON like:

{
    "method": "GET",
    "url": "asd",
    "headers": {
        "Content": "application/json",
        "Authorization": "token"
    }
}

You could use the function json-pretty-print-buffer-ordered or json-pretty-print-ordered from json.el. These functions won't work with most JavaScript code though because JSON has a stricter syntax. The sample code has unquoted keys and trailing commas which are perfectly valid JavaScript features (you just can't use JSON tools on it).

By no means is this a complete solution to your question (but it might be useful for some circumstances, so I figured it worth mentioning).

  • yes, I mean, is a js object, not a json – Daniel Pérez Jun 27 '18 at 13:38
  • @DanielPérez Sorry; I didn't mean to imply that there was anything wrong with your question or the code. I mention the json function since it might be useful for some edge cases. – ebpa Jun 27 '18 at 14:00
  • nothing to be sorry about ;) @ebpa , i find this answer useful, I searched for other similar questions and they suggested the use of json-pretty-print-buffer-ordered, I was hoping someone had to deal with this before ..., I think i'll take a different approach and just pass the region to other program that would parse it correctly. thanks btw – Daniel Pérez Jul 1 '18 at 1:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.