javascript - 如何使用 map 函数重新组装以下 json?
问题描述
我正在尝试从给定的 json 制作 json 格式
我在 nodejs 中使用 map 函数,但它不能正常工作。我在这里提供所有细节。我想要一个代码,它会给我所需的 json 格式。
给定 Json :
var x =
[
[
{
"title":"My feel about shape up",
"answer":"neutral",
"objectives":[
"Awareness"
]
},
{
"title":"How good is shape up ?",
"answer":"a",
"objectives":[
"Awareness"
]
}
],
[
{
"title":"My feel about shape up",
"answer":"neutral",
"objectives":[
"Awareness"
]
},
{
"title":"How good is shape up ?",
"answer":"Awareness",
"objectives":[
"Awareness"
]
}
]
];
我试过的代码:
result = x.map(function(subarray) {
var data = subarray.map(v =>{
const wd= {[v.title ]: v.answer}
return wd;
})
return data;
})
实际输出:
[ [ { 'My feel about shape up': 'neutral' },
{ 'How good is shape up ?': 'a' } ],
[ { 'My feel about shape up': 'neutral' },
{ 'How good is shape up ?': 'Awareness' } ] ]
预期输出:
[
{ 'My feel about shape up': 'neutral',
'How good is shape up ?': 'a' } ,
{ 'My feel about shape up': 'neutral',
'How good is shape up ?': 'Awareness' }
]
解决方案
您可以使用.map()
和.reduce()
方法来获得所需的输出:
const data = [[
{"title":"My feel about shape up", "answer":"neutral", "objectives":[ "Awareness"]},
{"title":"How good is shape up ?", "answer":"a", "objectives":[ "Awareness"]}
], [
{"title":"My feel about shape up", "answer":"neutral", "objectives":["Awareness"]},
{"title":"How good is shape up ?", "answer":"Awareness", "objectives":["Awareness"]}
]];
const result = data.map(
arr => arr.reduce((r, {title: k, answer: v}) => (r[k] = v, r), {})
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
推荐阅读
- angular - 如何将网格的 id 值传递给按钮?
- java - 尝试从文件中读取文本时出错
- python - 最小的缺失数字
- vue.js - 在 Workbox + Webpack 自定义 Service Worker 中导入模块
- asp.net-core - System.ObjectDisposedException:无法访问已处置的对象 asp.net-core-webapi
- android-webview - 在 Android 上的 pdf.js 中搜索 viewer.html 中的突出显示偏移量
- android - 我可以在没有实时数据库的情况下访问 Firebase 存储吗?
- scala - scala多模块项目中的依赖冲突
- excel - 使用maatwebsite/excel导出数据到excel没有保留每个数据单元格前面的间距或边距 | 拉拉维尔 | maatwebsite-excel
- amazon-web-services - “AWS Elasticache for Redis”是否支持“RedisGear”?