gpt4 book ai didi

javascript - 如何转换对象数组?

转载 作者:行者123 更新时间:2023-12-03 16:39:31 25 4
gpt4 key购买 nike

我有一个问题。

我有对象数组:

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 但没有用。

最佳答案

您可以将一个对象键入您的 form_filled_key。并在循环中使用键将对象添加到对象以对它们进行分组。最后,您的解决方案将在您构建的对象的 Object.values() 中:

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)

关于javascript - 如何转换对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56860975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com