I have a variable parks with the following:
let parks = [
{ id: 1, park_name: 'Average Park', review: [] },
{ id: 2, park_name: 'Better Park', review: [] },
{ id: 3, park_name: 'Cooler Park', review: [] },
{ id: 4, park_name: 'Dull Park', review: [] }
]
And another variable review with the following:
let review = [
{ id: 1, park_id: 1, comment: "It's an okay park. Seen better" },
{ id: 2, park_id: 1, comment: "Ehh, it's alright" },
{ id: 3, park_id: 2, comment: "It's pretty decent" },
{ id: 4, park_id: 3, comment: "Good not great" }
]
What I want to achieve is adding the review object to parks.review based on park_id == parks.id. Basically I want is this:
[
{ id: 1, park_name: 'Average Park', review: [{ id: 1, park_id: 1, comment: "It's an okay park. Seen better" }, { id: 2, park_id: 1, comment: "Ehh, it's alright" }] },
{ id: 2, park_name: 'Better Park', review: [{ id: 3, park_id: 2, comment: "It's pretty decent" }] },
{ id: 3, park_name: 'Cooler Park', review: [{ id: 4, park_id: 3, comment: "Good not great" }] },
{ id: 4, park_name: 'Dull Park', review: [] }
]
What is the best approach to take?
>Solution :
nested for of will be the easiest and straightforward way for scanning 2 arrays simultaneously and so something.
You can also do it in with a single loop and use _.find or filter to make the code look more elegant
let parks = [
{ id: 1, park_name: 'Average Park', review: [] },
{ id: 2, park_name: 'Better Park', review: [] },
{ id: 3, park_name: 'Cooler Park', review: [] },
{ id: 4, park_name: 'Dull Park', review: [] }
];
let reviews = [
{ id: 1, park_id: 1, comment: "It's an okay park. Seen better" },
{ id: 2, park_id: 1, comment: "Ehh, it's alright" },
{ id: 3, park_id: 2, comment: "It's pretty decent" },
{ id: 4, park_id: 3, comment: "Good not great" }
];
for(let park of parks) {
for(let review of reviews) {
if(park.id === review.park_id) {
park.review.push(review);
}
}
}
console.log(parks);