Home > Enterprise >  Sort deeply nested objects alphabetically by keys
Sort deeply nested objects alphabetically by keys

Time:04-29

We are using vue-i18n and maintain our messages within an js variable. This leads to deeply nested objects or key/value pairs.

const messages = {
  en: {
    message: {
      page1: {
        title: "Some title",
        button: {
          title: "Foo",
        },
        subpage: {
          ...
        }
      },
      ...
    },
  },
  de: {...},
};

As u can see, without an appropriate sorting this file will be really confusing. My idea is to sort the whole file alphabetically by keys.

Is there an algorithm/code that can be used for this? Or do I have to write it myself?

CodePudding user response:

You can do some recursivity like :

I used the following answer to write the order function

const order = (unordered) => Object.keys(unordered).sort().reduce(
  (obj, key) => {
    obj[key] = unordered[key];
    return obj;
  }, {}
);

const message = {
  fr: {
    message: "Bonjour",
    a: 1
  },
  en: {
    message: "Hello",
    a: {
      c: 1,
      b: 2
    }
  },
  es: "Hola"
}

const sortObjectDeeply = (object) => {
  for (let [key, value] of Object.entries(object)) {
    if (typeof(value) === "object") {
      object[key] = sortObjectDeeply(value)
    }
  }
  return order(object)
}

console.log(sortObjectDeeply(message))

  • Related