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?
CodePudding user response:
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).