如何从JSON键创建数组?API返回JSON转JS数组及安卓转JS困惑
Absolutely, extracting the keys of your diagnosis object into an array is completely feasible—JavaScript has a built-in method that makes this super straightforward.
1. Extracting Diagnosis Keys to Array
Given your API response structure:
{ "diagnosis": { "type": [], "kode": [], "PrimaryCat": [], "Location": [], "Encountrace": [], "Fracture": [], "Healing": [] } }
You can use the Object.keys() method to grab all the top-level keys of the diagnosis object directly:
// Assume this is your parsed API response data const apiResponse = { "diagnosis": { "type": [], "kode": [], "PrimaryCat": [], "Location": [], "Encountrace": [], "Fracture": [], "Healing": [] } }; // Extract the keys into your target array const diagnosisKeys = Object.keys(apiResponse.diagnosis); console.log(diagnosisKeys); // Output: ['type', 'kode', 'PrimaryCat', 'Location', 'Encountrace', 'Fracture', 'Healing']
That’s all it takes! Object.keys() returns an array of a given object's own enumerable property names, which matches exactly what you’re looking for.
2. Converting Android (Java/Kotlin) Logic to JavaScript
Since you mentioned struggling with converting your Android implementation, let’s cover a common scenario. For example, if your Android code looks like this (Kotlin):
val diagnosis = mapOf( "type" to emptyList<Any>(), "kode" to emptyList<Any>(), // ... other key-value pairs ) val diagnosisKeys = diagnosis.keys.toList()
Or in Java:
HashMap<String, List<Object>> diagnosis = new HashMap<>(); diagnosis.put("type", new ArrayList<>()); diagnosis.put("kode", new ArrayList<>()); // ... other key-value pairs List<String> diagnosisKeys = new ArrayList<>(diagnosis.keySet());
The JavaScript equivalent is exactly the Object.keys() approach shown above. If your Android code includes more complex logic—like filtering specific keys, transforming values, or handling nested data—share that specific snippet, and I can help translate it directly to JavaScript.
内容的提问来源于stack exchange,提问作者flix

