0

Lets say I have a JSON object like:

var objDBandIDs = {"vcFirstName":"enFN"
                    ,"vcSurName":"enSN"
                        ,"vcSex":["rdoM", "rdoF"]
                  ,"intEmployed":"enEmp"
                    ,"vcAddress":"enADR"};

In JavaScript I can iterate through this object using:

for( var strKey in objDBandIDs ) {
    var rightSide = objDBandIDs[strKey];
    ...
}

Where strKey is the label e.g. vcFirstName, rightSide would be enFN.

Is there a way to create a loop that instead of the left as an iterator, the right side is used to iterate through the JSON?

SPlatten
  • 5,334
  • 11
  • 57
  • 128
  • 1
    JSON is a *textual notation* for data exchange. [(More here.)](http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. – T.J. Crowder Dec 11 '21 at 11:51

1 Answers1

0

You can't use the value as the key because values, unlike keys, may not be unique.

You can loop through just the values by looping through the result of Object.values:

for (const value of Object.values(objDBandIDs)) {
    // ...
}

Live Example:

const objDBandIDs = {
    "vcFirstName": "enFN",
    "vcSurName": "enSN",
    "vcSex": ["rdoM", "rdoF"],
    "intEmployed": "enEmp",
    "vcAddress": "enADR"
};
for (const value of Object.values(objDBandIDs)) {
    console.log(value);
}

Or you can loop through both using the result of Object.entries:

for (const [key, value] of Object.entries(objDBandIDs)) {
    // ...
}

Live Example:

const objDBandIDs = {
    "vcFirstName": "enFN",
    "vcSurName": "enSN",
    "vcSex": ["rdoM", "rdoF"],
    "intEmployed": "enEmp",
    "vcAddress": "enADR"
};
for (const [key, value] of Object.entries(objDBandIDs)) {
    console.log(key, value);
}

In both cases, you don't have to use a for..of loop, you can use any array looping mechanism (see my answer here for options).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875