In an array of objects
I am trying to create a new property based on another array of numbers
.
The problem is that the number of array
has one less element, therefore it gets undefined
in the last index of array of objects
.
How to handle that case, if the new created property is undefined
? See the code example below
const sortArr = [3, 2, 1];
const items= [
{
a: 1,
},
{
a: 2,
},
{
a: 3,
},
{
a: 4,
},
];
const res =
items.map((item, idx) => ({
...item,
sortItem:sortArr[idx]
}));
console.log(res)
CodePudding user response:
if it's the last in the array then show nothing/empty string
To use an empty string as fallback if sortArr[inx]
does not exist, use the Nullish coalescing operator (??
) operator:
sortItem: sortArr[idx] ?? ''
const sortArr = [3, 2, 1];
const items= [{a: 1, }, {a: 2, }, {a: 3, }, {a: 4, }, ];
const res = items.map((item, idx) => (
{
...item,
sortItem: sortArr[idx] ?? ''
}
));
console.log(res)
CodePudding user response:
You can set sortItem based on whether idx is less than sortArr.length
sortItem: idx < sortArr.length ? sortArr[idx] : "no element at that position"