我有一个
格式的JSON数据[{
"Heading1": [{
"questionID": "q1",
"questionTitle": "Question 1",
"question": "This is question1",
"status": 0,
"files": [],
"uploadType": "none"
}, {
"questionID": "q2",
"questionTitle": "Question 2",
"question": "This is question2",
"status": 0,
"files": [],
"uploadType": "none"
}]
}, {
"Heading2": [{
"questionID": "q3",
"questionTitle": "Question 11",
"question": "This is a question11",
"status": 0,
"files": [],
"uploadType": "none"
}]
}, {
"Heading3": [{
"questionID": "q4",
"questionTitle": "Question 1",
"question": "This is a question",
"status": 0,
"files": [],
"uploadType": "none"
}]
}]
我正在尝试以[{"Title":"Heading1"},{"Title":"Heading2"},{"Title":"Heading3"}]
我应该怎么做?
答案 0 :(得分:0)
首先,如果您确实有JSON(例如,您的起点是一个字符串,例如来自ajax响应的字符串),则可以通过JSON.parse
对其进行解析以获取对象数组。然后循环数组,并通过Object.keys(x)[0]
从每个顶级对象中获取唯一键,并将其映射到所需形式的对象数组:
const json = '[{"Heading1":[{"questionID":"q1","questionTitle":"Question 1","question":"This is question1","status":0,"files":[],"uploadType":"none"},{"questionID":"q2","questionTitle":"Question 2","question":"This is question2","status":0,"files":[],"uploadType":"none"}]},{"Heading2":[{"questionID":"q3","questionTitle":"Question 11","question":"This is a question11","status":0,"files":[],"uploadType":"none"}]},{"Heading3":[{"questionID":"q4","questionTitle":"Question 1","question":"This is a question","status":0,"files":[],"uploadType":"none"}]}]';
const parsed = JSON.parse(json);
const result = parsed.map(entry => {
return {Title: Object.keys(entry)[0]};
});
console.log(result);
map
回调可以是一个简洁的箭头函数,但我认为使用上面的详细形式会更清楚。简洁的形式是:
const result = parsed.map(entry => ({Title: Object.keys(entry)[0]}));
请注意,以这种方式使用Object.keys
只有在对象确实只有一个属性的情况下才是可靠的,如您所问的那样。如果它们具有多个属性,则Object.keys
中数组中列出的属性的顺序未定义(即使在ES2015 +中,属性确实具有顺序-不需要Object.keys
遵循该顺序[尽管它在我测试过的每个现代引擎上都可以使用]。