使用一系列对象,如:
const activities = [{
id: 11129,
recap: {
id: 11129,
recapValues: [
{
id: 1,
internalName: 'Foo',
},
{
id: 2,
internalName: 'Bar',
},
{
id: 6,
internalName: 'Bongo',
},
],
},
},
{
id: 11130,
recap: {
id: 11130,
recapValues: [
{
id: 4,
internalName: 'Bingo',
},
{
id: 5,
internalName: 'Bango',
},
{
id: 6,
internalName: 'Bongo',
},
],
},
}]
我的目标是通过匹配参考对象数组中的responseOptions
键,向每个嵌套的constraints
键添加一个recapValues
和internalName
键:
const questions = [{
internalName: 'Foo',
responseOptions: null,
constraints: {
date: {},
},
},
{
internalName: 'Bar',
responseOptions: {},
constraints: null,
},
{
internalName: 'Bango',
responseOptions: null,
constraints: null,
},
{
internalName: 'Bingo',
responseOptions: {},
constraints: null,
},
{
internalName: 'Bongo',
responseOptions: null,
constraints: {
time: {},
},
}]
预期的结果:
[{
id: 11129,
recap: {
id: 11129,
recapValues: [
{
id: 1,
internalName: 'Foo',
responseOptions: null,
constraints: {
date: {},
},
},
{
id: 2,
internalName: 'Bar',
responseOptions: {},
constraints: null,
},
{
id: 6,
internalName: 'Bongo',
responseOptions: {},
constraints: {
time: {},
},
},
],
},
},
{
id: 11130,
recap: {
id: 11130,
recapValues: [
{
id: 4,
internalName: 'Bingo',
responseOptions: null,
constraints: null,
},
{
id: 5,
internalName: 'Bango',
responseOptions: {},
constraints: null,
},
{
id: 6,
internalName: 'Bongo',
responseOptions: {},
constraints: {
time: {},
},
},
],
},
}]
我的尝试导致下面的代码为每个responseOptions
对象仅添加一次constraints
和recapValues
键,而不为recapValues
内部的每个问题添加一次:< / p>
activities.map(activity => ({
...activity,
recap: {
...activity.recap,
recapValues: [
...activity.recap.recapValues,
...activity.recap.recapValues
.forEach(q => questions
.find(obj => obj.internalName === q.internalName)),
],
},
}))
我错过了什么阻止了预期的结果?
答案 0 :(得分:2)
forEach
返回undefined
,而您想map
recapValues:
activities.map(activity => ({
...activity,
recap: {
...activity.recap,
recapValues: activity.recap.recapValues.map(value => ({
...value,
...questions.find(obj => obj.internalName === value.internalName),
}),
},
}))
我们可以通过使用映射函数来美化一下:
const mapObj = (key, mapper) => ({ [key]: val, ...rest }) => ({ [key]: mapper(val), ...rest });
const map = mapper => arr => arr.map(mapper);
const format = map(
mapObj("recap",
mapObj("recapValues",
map(value => ({
...value,
...questions.find(q => q.internalName === value.internalName)
}))
)
)
);
const output = format(activities);