skip to Main Content

i have an object

const data = {
  "name-uz": "name uz",
  "desc-uz": "<p>desc uz</p>rn",
  "name-en": "name en",
  "desc-en": "<p>desc en</p>rn",
  days: "5",
  price: "2000",
  extra_price: "1000",
};

i want to do this thing:

{
  name: {
    uz: "name-uz",
    en: "name-en"
  }
  desc: {
    uz: "desc-uz",
    en: "desc-en"
  }
}

how can i achieve this?

i have no idea what to do…

2

Answers


  1. Use Object.keys to iterate through object properties

    Use String.prototype.split to split the string

    const data = {
      "name-uz": "name uz",
      "desc-uz": "<p>desc uz</p>rn",
      "name-en": "name en",
      "desc-en": "<p>desc en</p>rn",
      days: "5",
      price: "2000",
      extra_price: "1000",
    };
    
    const obj = {}
    
    for (const key of Object.keys(data)) {
      if (!key.includes('-')) continue
      const [part1, part2] = key.split('-')
      if (!(part1 in obj)) obj[part1] = {}
      obj[part1][part2] = key
    }
    
    console.log(obj)
    Login or Signup to reply.
  2. Here is the shortest I could come up with.

    I am assuming you have a name and a description in two languages and not just name uz and desc uz

    const stripHTML = (html) => {
      const temp = document.createElement("div");
      temp.innerHTML = html;
      return temp.textContent?.trim() ?? "";
    };
    
    const newData = {};
    
    Object.keys(data).forEach((key) => {
      const [type, lang] = key.split("-");
      if (lang) {
        newData[type] ??= {};
        newData[type][lang] = type.startsWith("desc") ? stripHTML(data[key]) : data[key];
      }
    });
    
    console.log(newData);
    <script>
    const data = {
      "name-uz": "Do'st",
      "desc-uz": "<p>Tez jigarli tilov terishib, bu bo'ri yuguradi.</p>rn",
      "name-en": "Buddy",
      "desc-en": "<p>The quick brown fox jumps over the lazy dog.</p>rn",
      days: "5",
      price: "2000",
      extra_price: "1000",
    };
    </script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search