Untitled
unknown
javascript
2 years ago
2.3 kB
7
Indexable
// Define a recursive function to convert JSON function convertJSONRecursive(inputJSON) { // Check if the input is an object if (typeof inputJSON === "object") { // Check if the input is an array if (Array.isArray(inputJSON)) { // Initialize a new JSON object const newJSON = {}; // Iterate over each item in the input array for (const item of inputJSON) { // Check if the item has an id if (item.id) { // Get the first operation allowed for the item const operation = item.operationsAllowed[0]; // If the operation does not exist in the new JSON object, initialize it as an array if (!newJSON[operation]) { newJSON[operation] = []; } // Create a new item with the id and operations allowed from the original item const newItem = { id: item.id, operationsAllowed: item.operationsAllowed, }; // If the item has other allowed filters and they are an array, set them to null in the new item if (item.otherAllowedFilters && Array.isArray(item.otherAllowedFilters)) { newItem.otherAllowedFilters = null; } else { // Otherwise, recursively convert the other allowed filters newItem.otherAllowedFilters = convertJSONRecursive(item.otherAllowedFilters); } // Add the new item to the operation in the new JSON object newJSON[operation].push(newItem); } } // Return the new JSON object return newJSON; } else { // If the input is not an array, initialize a new JSON object const newJSON = {}; // Iterate over each key in the input object for (const key in inputJSON) { // Recursively convert the value of the key and add it to the new JSON object newJSON[key] = convertJSONRecursive(inputJSON[key]); } // Return the new JSON object return newJSON; } } else { // If the input is not an object, return the input as is return inputJSON; } } // Define the input JSON object const inputJSON = { // ... }; // Call the function with the input JSON object and log the result const convertedJSON = convertJSONRecursive(inputJSON); console.log(JSON.stringify(convertedJSON, null, 2));
Editor is loading...