简体   繁体   中英

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);

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)

I am not 100% sure what you are asking, but you can use a for...in loop to do what I think you are asking. for...in loops are an easy way to loop over an object. See below for example where I log out the key and the value.

 var javaObj = '{ "LastName": "LN", "FirstName": "FN", "MiddleName": "MN"}'; var obj = JSON.parse(javaObj); var text = ''; for(var item in obj) { console.log(item + " " + obj[item]) text += obj[item]; } console.log(text);

You can code objText += [obj.PersonArrayKeys[j]];

 var PersonArrayKeys = ["LastName", "FirstName", "MiddleName"]; var javaObj = '{ "LastName": "LN", "FirstName": "FN", "MiddleName": "MN"}'; var obj = JSON.parse(javaObj); console.log(obj); var objText=''; for (j = 0; j < PersonArrayKeys.length; j++) { objText += obj[PersonArrayKeys[j]]; } console.log(objText)

You can deconstruct the object. Since you know the keys, I suggest the following...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM