首页 > 解决方案 > 如何使用 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' } 
]

标签: javascriptarraysjsonobject

解决方案


您可以使用.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; }


推荐阅读