0

I have an array of objects :

let formInputs = [
    {"name" : "NOM_MANDATAIRE", "fieldType": "input", "type": "text", "values": []},
    {"name" : "SECTEUR_VENTE", "fieldType": "select", "type": null, "values": [
        {"key": "1", "value": "text of the select"},
        {"key": "2", "value": "text of the select"}
    ]},
    {"name" : "TITRE_VERSION", "fieldType": "input", "type": "text", "values": []},
];

I use a forEach to get each objects and manipulate them :

formInputs.forEach(element => {
    console.log(element.name);
    ...
    for (let items in element.values) {
        for (item in items) {
            console.log(item.key);
        }
    }
}

My issue is that i'm stuck when I want to retrieve the object associated to the key "values". In the forEach block i also tried to use a for each :

item returns 0 and item.key returns undefined.

davidvera
  • 1,292
  • 2
  • 24
  • 55
  • The problem is you're using `for-in` to loop through an array. That's almost never what you want, `items` in your outer loop is a *string* containing the value `"0"`, then `"1"`, etc. In ES2015+ (which you seem to be using), `for-of` is what you're looking for, but see the linked question's answers for more options. Basically: ```for (const {values} of formInputs) { for (const entry of values) { /* ... */ } }``` https://pastebin.com/PYSGa2gG Or that inner one might be `for (const {key} of values) { /*...*/ }` if you just want the `key`. – T.J. Crowder Nov 22 '19 at 12:03
  • 1
    Try this.. formInputs.forEach(element => { for (let item of element.values) { console.log("key=", item['key']); console.log("value=", item['value']); } }); – hbamithkumara Nov 22 '19 at 12:10
  • your let item of element.values work fine ! thanks ! I'm always confused with for in and of. – davidvera Nov 22 '19 at 13:36

0 Answers0