I have a sorted array of books with a property called 'place'.
book:
{
id : number,
place: string
}
but then I also have an array of places with the property 'name'
place
id: number,
name: string
What I'd like to do is to manipulate the array of books so that in the exact order, the place property in a book takes the name value of the place object
result should be:
booksArr[0] == placeArr[0].name
booksArr[1] == placeArr[1].name
booksArr[2] == placeArr[2].name
and if the length of the placeArr > booksArr, then it should just ignore the rest, not do anything with it.
Is there any nifty way of doing that?
CodePudding user response:
book.forEach((_, ind) => {
book[ind]["place"] = place[ind]["name"]
});
CodePudding user response:
How about:
const books = [...] // Your array of books
const places = [...] // Your array of places
books = books.map((book) => ({ id: book.id, place: places.find((place) => place.id === book.place)) });
CodePudding user response:
You could iterate and use a short circuit for unequal arrays.
placeArray.some(({ name }, i) => {
booksArray[i].place = name;
return i 1 >= booksArray.length;
});
CodePudding user response:
Yep, there's a pretty straightforward way to do that. You can use Array.prototype.map() to create another array, with the values you want.
const booksWithPlace = booksArr.map((book, index) => {...book, place: placeArr[index]})