0

I have this JSON object, and I would like to replace all 'title' and 'description' objects with title.es and description.es child values, somehow like this: item.title = item.title.es Could you help me to find the correct recursive algorithm? I tried to use recursive functions, but didn't worked.

[
  {
    "name": "aaa",
    "title": {
      "es": "dfghfdghgfhgfh",
      "en": "hjklhjkljkhljkhlklj"
    },
    "services": [
      {
        "name": "aaa-1",
        "title": {
          "es": "dfgdfgsdfg",
          "en": "dfghfgdhgfhgfhgf"
        },
        "services": [
          {
            "name": "aaa-1-1",
            "title": {
              "es": "dfghgfhfghgfdh",
              "en": "dfghfgdhfgdhgfdh"
            }
            "description": {
              "es": "sdfgfdsgfdg",
              "en": "sertztrezrteztre"
            }
          }
        ]
      },
      {
        "name": "aaa-2",
        "title": {
          "es": "ertzrtez",
          "en": "ertuztzutzuztuzt"
        }
      },
    ]
  },
  {
    "name": "bbb",
    "title": {
      "es": "sdfsdfdsf",
      "en": "sdfsdfdsfdsfdsf"
    },
    "services": [
      {
        "name": "bbb-1",
        "title": {
          "es": "sdfsdfdsfdsf",
          "en": "sdfdsfdsfds"
        },
        "services": [
          {
            "name": "bbb-1-1",
            "title": {
              "es": "werwerewrewr",
              "en": "werwerwerwerew"
            }
          },
          {
            "name": "bbb-1-2",
            "title": {
              "es": "werewrewrwerewr",
              "en": "werewrewrewrwerwerwerwerewr"
            }
          }
        ]
      }
    ]
  }
]
1
  • Welcome to SO! "I tried to use recursive functions, but didn't worked" -- could you share the attempts? Thanks. Commented Jul 13, 2021 at 18:33

1 Answer 1

0

This should do the trick for recursive function:


function iter(o) {
  Object.keys(o).forEach((k) => {
    console.log(k);
    if (k === 'title' || k === 'description') {
      console.log(o[k]);
      o[k] = o[k].en;
      return;
    }
    if (o[k] !== null && typeof o[k] === 'object') {
      iter(o[k]);
    }
  });
}
iter(obj);

This is a modified version of: another SO answer :)

Sign up to request clarification or add additional context in comments.

2 Comments

Parsing error: Unexpected token :
can you please update your question first to post the solution you have tried?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.