In my programming code, I work with two separate JSON files. I iterate through each item in the first file and compare its values with those in the second file. Based on the comparison results, I generate a third JSON file which essentially merges the contents of the first two files.
When comparing the values, I use the Object.values method to extract the value of the current entry. For simple string or integer values, it works as expected:
var json = '{ "key":"Team" }';
json = JSON.parse(json);
var value = Object.values(json)[0]; //Output: Team
However, when dealing with an array, the output is not ideal:
var json = `{ "key":"Team", "default value":["Team Red","Team Blue"] }`;
json = JSON.parse(json);
var key = Object.values(json)[0];
var defaultValue = Object.values(json)[1];
console.log(key + " --- " + defaultValue); //Output: Team --- Team Red, Team Blue
The issue arises when creating the third JSON file from this data. The new file ends up having {"default value": "Team Red, Team Blue"} instead of the desired format {"default value": ["Team Red", "Team Blue"]}.
I am seeking a way to determine if the current value is a JSON array so that I can preserve it as an array in the resulting third file, rather than just a simple string. Any insights or suggestions would be greatly appreciated.
UPDATE
Thanks to the helpful responses, I now understand the distinction between the console.log output formats based on whether additional strings are included. However, this knowledge doesn't fully address my challenge of properly structuring the third JSON file.
Since I still need to stringify the array for the new file, I'm looking for a method to represent an array like ["Team Red", "Team Blue"]
as a string while retaining the square brackets and quotation marks without losing them. While iterating through the array and reconstructing it manually is an option using Array.isArray(), I am curious if there is a more efficient approach available.