Search code examples
javascriptjsonfor-loopkeyvaluepair

How to use a JavaScript array to retrieve a JSON object's values all at once via a for loop


Is there a way, in JavaScript, to use an array to loop through and retrieve a JSON object's values in a for loop in one go?

I have one array dedicated to the keys in my JSON object:

var PersonArrayKeys = ["LastName", "FirstName", "MiddleName"];

And my JSON object:.

var javaObj = '{ "LastName": "LN", "FirstName": "FN", "MiddleName": "MN"}'
var obj = JSON.parse(javaObj);

I can get the value if I just refer to the object's key like so,

console.log(obj.LastName);

But if possible I'd like to get all of them in one go. This was the only thing I could think of, but it gives an "Unexpected token : in JSON."

var objText;
for (j = 0; j < PersonArrayKeys.length; j++) {
     console.log(PersonArrayKeys[j] + " key");
     objText += obj.PersonArrayKeys[j];
}
console.log(objText);

Solution

  • You could also use this oneliner instead of the loops - it enumerates all the value and merge them into one string.

    var objText = Object.values(obj).join(' ')
    console.log(objText)