i have a problem.
I have that array of objects:
const iHaveThis = [{
question: "What's your name?",
answer: 'dda',
form_filled_key: 15,
},
{
question: "What's your e-mail?",
answer: '[email protected]',
form_filled_key: 15,
},
{
question: "What's your e-mail?",
answer: '[email protected]',
form_filled_key: 14,
},
{
question: "What's your name?",
answer: 'DAS',
form_filled_key: 14,
},
];
I want transform it to:
const iWillHaveThis = [{
"What's your e-mail?": '[email protected]',
"What's your name?": 'dda',
},
{
"What's your e-mail?": '[email protected]',
"What's your name?": 'DAS',
},
];
How can i make that ? Please
I already tried use reduce, map but not working.
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: '[email protected]',form_filled_key: 15,},
{question: "What's your e-mail?",answer: '[email protected]',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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With