如何转换对象数组?
问题描述:
我有问题。
我有该对象数组:
const iHaveThis = [{
question: "What's your name?",
answer: 'dda',
form_filled_key: 15,
},
{
question: "What's your e-mail?",
answer: 'sda@br.com',
form_filled_key: 15,
},
{
question: "What's your e-mail?",
answer: 'dAS@be.bimc',
form_filled_key: 14,
},
{
question: "What's your name?",
answer: 'DAS',
form_filled_key: 14,
},
];
我想将其转换为:
const iWillHaveThis = [{
"What's your e-mail?": 'sda@br.com',
"What's your name?": 'dda',
},
{
"What's your e-mail?": 'dAS@be.bimc',
"What's your name?": 'DAS',
},
];
我该怎么做?请
我已经尝试使用reduce,map,但无法正常工作。
I already tried use reduce, map but not working.
答
您可以创建一个键为 form_filled_key
的对象。并在循环中使用键将对象添加到对象中以对它们进行分组。最后,您的解决方案将在所构建对象的 Object.values()
中:
You can make an object keyed to your form_filled_key
. And in a loop add objects to the object using the key to group them. In the end, your solution will be in the Object.values()
of the object you built:
const iHaveThat = [
{question: "What's your name?",answer: 'dda',form_filled_key: 15,},
{question: "What's your e-mail?",answer: 'sda@br.com',form_filled_key: 15,},
{question: "What's your e-mail?",answer: 'dAS@be.bimc',form_filled_key: 14,},
{question: "What's your name?",answer: 'DAS',form_filled_key: 14,},];
let arr = iHaveThat.reduce((obj, {form_filled_key, question, answer}) => {
// make a new entry if needed
if (!obj[form_filled_key]) obj[form_filled_key] = {}
// add the key value pair
obj[form_filled_key][question] = answer
return obj
},{})
// you just want the array from `values()`
let result = Object.values(arr)
console.log(result)