Общее c решение для произвольных случаев
function buildItems(obj) {
const commonPairs = Object.entries(obj).reduce(
(accumulate, [key, val]) =>
Array.isArray(val) ? accumulate : { ...accumulate, [key]: val },
{}
)
const arrayPairs = Object.entries(obj).reduce(
(accumulate, [key, val]) =>
!Array.isArray(val) ? accumulate : { ...accumulate, [key]: val },
{}
)
if (Object.keys(arrayPairs).length === 0) {
return [{ ...commonPairs }]
}
const res = []
for (let i = 0; i < arrayPairs[Object.keys(arrayPairs)[0]].length; i++) {
res.push({
...commonPairs,
...Object.keys(arrayPairs).reduce(
(acc, key) => ({ ...acc, [key]: arrayPairs[key][i] }),
{}
),
})
}
return res
}
console.log(
"1)",
buildItems({
prop1: "value1",
prop2: "value2",
nested1: [{ A: 1 }, { B: 1 }, { G: 1 }],
nested2: [{ C: 1 }, { D: 1 }, { H: 1 }],
nested3: [{ E: 1 }, { F: 1 }, { I: 1 }],
nested4: [{ J: 1 }, { K: 1 }, { L: 1 }],
nested5: [{ M: 1 }, { N: 1 }, { O: 1 }],
}),
"\n"
)
console.log(
"2)",
buildItems({
prop1: "value1",
prop2: "value2",
}),
"\n"
)
console.log(
"3)",
buildItems({
prop1: "value1",
prop2: "value2",
nested1: [{ A: 1 }, { B: 1 }, { G: 1 }],
}),
"\n"
)