gpt4 book ai didi

javascript - 在数组中的对象中映射对象

转载 作者:行者123 更新时间:2023-11-30 19:57:31 24 4
gpt4 key购买 nike

我有一个数组,其中包含一个对象,其中包含我想映射到更简单结构的更多对象。

我尝试了以下内容,它似乎循环遍历对象并为每个循环返回一个没有数据的对象。

Object.values(data).forEach((a) => {
console.log({
managingRole: a.id === 110 ? a.answer : null,
advice: a.id === 112 ? a.answer : null,
});
});

最终目标是返回一个对象数组来映射:

const desired = [{
managingRole: 'spending',
advice: 'everyone'
},
{
managingRole: 'saving',
advice: 'no one'
}];

我使用的数据如下:

const data = [{
'110':
{
id: 110,
type: 'RADIO',
question: '<strong>My main role in managing my money is:</strong>',
section_id: 9,
answer: 'spending'
},
'111':
{
id: 111,
type: 'RADIO',
question: '<strong>When it comes to financial matters, I most agree with which statement?</strong>',
section_id: 9,
answer: 'spend it'
},
'112':
{
id: 112,
type: 'RADIO',
question: '<strong>When deciding on an investment, I trust the advice of :</strong>',
section_id: 9,
answer: 'everyone'
}
},
{
'110':
{
id: 110,
type: 'RADIO',
question: '<strong>My main role in managing my money is:</strong>',
section_id: 9,
answer: 'saving'
},
'111':
{
id: 111,
type: 'RADIO',
question: '<strong>When it comes to financial matters, I most agree with which statement?</strong>',
section_id: 9,
answer: 'save it'
},
'112':
{
id: 112,
type: 'RADIO',
question: '<strong>When deciding on an investment, I trust the advice of :</strong>',
section_id: 9,
answer: 'no one'
}
}];

最佳答案

您可以使用给定的 id 直接寻址对象,这与具有所需 answer 的对象的键相同。

const
data = [{ 110: { id: 110, type: 'RADIO', question: '<strong>My main role in managing my money is:</strong>', section_id: 9, answer: 'spending' }, 111: { id: 111, type: 'RADIO', question: '<strong>When it comes to financial matters, I most agree with which statement?</strong>', section_id: 9, answer: 'spend it' }, 112: { id: 112, type: 'RADIO', question: '<strong>When deciding on an investment, I trust the advice of :</strong>', section_id: 9, answer: 'everyone' } }, { 110: { id: 110, type: 'RADIO', question: '<strong>My main role in managing my money is:</strong>', section_id: 9, answer: 'saving' }, 111: { id: 111, type: 'RADIO', question: '<strong>When it comes to financial matters, I most agree with which statement?</strong>', section_id: 9, answer: 'save it' }, 112: { id: 112, type: 'RADIO', question: '<strong>When deciding on an investment, I trust the advice of :</strong>', section_id: 9, answer: 'no one' } }],
result = data.map(o => ({
managingRole: o['110'].answer || null,
advice: o['112'].answer || null
}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 在数组中的对象中映射对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53785777/

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