如何转换JSON数据结构?对象转数组格式技术求助
解决方案
Got it, let's fix this data structure conversion for you! This is a common task, and here are simple, clean solutions in two widely used languages to get your data into the desired array format.
JavaScript 实现
We can use Object.entries() to extract key-value pairs from the original object, then map() to transform each pair into the structure you need:
const originalData = { "key1": { "description":"lorem ipsum", }, "key2": { "description":"lorem ipsum", } }; const convertedData = Object.entries(originalData).map(([label, value]) => ({ label, description: value.description })); // Output will match your desired structure console.log(convertedData);
How it works:
Object.entries(originalData)converts the object into an array of[key, value]pairs (e.g.,["key1", { description: "lorem ipsum" }]).- The
map()method iterates over each pair, destructures the key intolabeland the value object, then returns a new object with your required fields.
Python 实现
For Python, we'll use a list comprehension to iterate over the dictionary's items and build the target array:
original_data = { "key1": { "description":"lorem ipsum", }, "key2": { "description":"lorem ipsum", } } converted_data = [ {"label": key, "description": value["description"]} for key, value in original_data.items() ] # Prints your desired array structure print(converted_data)
How it works:
original_data.items()gives us each key-value pair in the dictionary.- The list comprehension creates a new dictionary for each pair, using the key as
labeland pulling thedescriptionfrom the nested value object.
Both solutions are flexible—if you ever need to include additional fields from the nested objects, just add them to the returned object/dictionary in the transformation step.
内容的提问来源于stack exchange,提问作者Galactic Ranger




