Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I push an object in an array of objects to an array within another array of object?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
  { 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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading