1

I'm having troubles itinerating on a json, it looks like this:

{
"name":"Meeting 2021",
"translate": {"de":okay","fr":"okay2"}
}

I'm trying create a for on the translate key.

I tried the following but I end up splitting the strings letter by letter:

 var arr = JSON.parse(responsex.translate);

    arr.forEach(function (elementObject) {
        var keys = Object.keys(elementObject);
        keys.forEach(function (key) {
        console.log(key + ':' + elementObject[key]);
         })
   });

I also tried doing a simple for but I'm getting undefined index. What exactly am I doing wrong? I'm simply trying to get the DE and FR values individually so I can make a simple html select.

Thank you!

johnnasx
  • 158
  • 10
  • You could use `for (let item of items) {...}` instead of the "old school" method. It is easyer to work with IMHO. – Frizzant Mar 30 '21 at 09:53

1 Answers1

1

The issue in your code is that you're attempting to loop through an object as if it's an array. The two are not analogous data structures.

Instead you can use Object.keys() to get the keys from the translate property, then loop through them:

let obj = {
  "name": "Meeting 2021",
  "translate": {
    "de": "okay",
    "fr": "okay2"
  }
}

Object.keys(obj.translate).forEach(k => {
  console.log(`${k}: ${obj.translate[k]}`);
});

Assuming you don't need IE support you can use the more modern Object.entries() method:

let obj = {
  "name": "Meeting 2021",
  "translate": {
    "de": "okay",
    "fr": "okay2"
  }
}

for (const [key, value] of Object.entries(obj.translate)) {
  console.log(`${key}: ${value}`);
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339