Как я могу собрать следующий JSON с помощью функции карты? - PullRequest
2 голосов
/ 26 мая 2019

Я пытаюсь сделать формат JSON из данного JSON

Я использую функцию карты в nodejs, но она работает неправильно. Я даю все детали здесь. Я хочу код, который даст мне необходимый формат 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' } 
]

Ответы [ 3 ]

1 голос
/ 26 мая 2019

Вы возвращаете массив из цикла, вместо этого вам нужно создать объект, чтобы получить желаемый результат,

let 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"]}]];

let final = data.map(value =>
  value.reduce((op, {title, answer}) => {
    op[title] = answer
    return op
  },{})
)
console.log(final)
1 голос
/ 26 мая 2019

Вы можете использовать .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; }
0 голосов
/ 26 мая 2019

Вы должны использовать reduce для подмассивов, чтобы получить один объект для каждого подмассива;

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"]}]];
const res = x.map(e => e.reduce((acc, { title, answer }) => ({ ...acc, [title]: answer }), {}));
console.log(res);

Синтаксис ES5:

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"]}]];
var res = x.map(function(e) {
  return e.reduce(function(acc, curr) {
    return Object.assign({}, acc, { [curr.title]: curr.answer });
  }, {});
});
console.log(res);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...