Hello developers Im trying to map the key value i have in an array of objects , into other array of minor length, but due to the task i have been committed is necessary to do it in this way.
Lets say i Have an array of objects of length 2 with this structure:
const array1=[
{ status: "ok", actual: true },
{ status: "not ok" },
]
And the array i pretend to add to this one has a bigger length and look like this:
const iconsStepper = [
{ icon: 'x' },
{ icon: 'xx' },
{ icon: 'xxx' }
];
Then the expected result , having in mind i need to couple the second array into the first would be :
[
{ status: "ok", actual: true ,icon:x},
{ status: "not ok",icon:xx },
{icon:xxx },
]
I got a function mapping the second array into the first:
array1.map((object, index) => ({
...object,
icon: iconsStepper[index].icon,
}));
and following this logic the result thrown is :
[
{ status: "ok", actual: true ,icon:x},
{ status: "not ok",icon:xx },
]
Being omitted the last object of the iconSteeper array cause the length of the array it supposed should be mapped to is minor
How can i fix this problem without precisely invert the array to map. Thanks
You could mege the arrays by reducing them and get all property of the same indices at the same place.
const
array1 = [{ status: "ok", actual: true }, { status: "not ok" }],
array2 = [{ icon: 'x' }, { icon: 'xx' }, { icon: 'xxx' }],
result = [array1, array2].reduce((r, a) => {
for (let i = 0; i < a.length; i++) Object.assign(r[i] ??= {}, a[i]);
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
A slightly different approach with mapping the arrays.
const
array1 = [{ status: "ok", actual: true }, { status: "not ok" }],
array2 = [{ icon: 'x' }, { icon: 'xx' }, { icon: 'xxx' }],
result = [array1, array2].reduce((r, a) => Object.assign(
r,
a.map((o, i) => ({...r[i], ...o }))
), []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
const array1 = [
{ status: "ok", actual: true },
{ status: "not ok" },
];
const iconsStepper = [
{ icon: 'x' },
{ icon: 'xx' },
{ icon: 'xxx' },
];
const output = array1.length > iconsStepper.length ? array1.map((object, index) => {
const returnObj = {
...object,
}
if (iconsStepper[index]) {
returnObj['icon'] = iconsStepper[index].icon
}
return returnObj;
}) : iconsStepper.map((object, index) => ({
...array1[index],
icon: iconsStepper[index].icon,
}));
console.log(output)
You can combine Array#reduce() and Array#map() as follows:
const arr1 = [{status: "ok", actual: true },{ status:"not ok" }];
const arr2 = [{ icon: 'x' },{ icon: 'xx' },{ icon: 'xxx' }];
const result = [arr1, arr2].reduce(
(acc,cur) => !acc.length ? cur : cur.map((e,i) => ({...acc[i],...e})), []
);
console.log( result );