Is there a way to add an object from one array of objects into a nested array within another array of objects?

I am dealing with two variables in my code: parks and review.

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 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" }
]

I want to add the objects from the review variable to the parks.review array based on matching park IDs.

[
  { 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 would be the most effective way to achieve this?

Answer №1

Utilizing a nested for of loop is the most straightforward method to iterate through two arrays simultaneously and perform an action.

If you prefer a more elegant approach, you can achieve the same result with a single loop by using methods like _.find or filter.

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);

Answer №2

If you want to efficiently process both arrays, consider iterating through them only once.

Use the parks array to create a reference based on the park's id, then add all reviews to their corresponding parks using this reference.

const
    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: [] }],
    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" }],
    parkIds = Object.fromEntries(parks.map(o => [o.id, o]));

review.forEach(o => parkIds[o.park_id].review.push(o));

console.log(parks);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

Here's a quick approach I thought of:

const gardens = [
  { id: 1, garden_name: "Standard Garden", feedback: [] },
  { id: 2, garden_name: "Enhanced Garden", feedback: [] },
  { id: 3, garden_name: "Sophisticated Garden", feedback: [] },
  { id: 4, garden_name: "Bland Garden", feedback: [] },
];

const feedbacks = [
  { id: 1, garden_id: 1, review: "It's an average garden. Have seen better ones." },
  { id: 2, garden_id: 1, review: "Well, it's not bad" },
  { id: 3, garden_id: 2, review: "Pretty decent overall" },
  { id: 4, garden_id: 3, review: "Good but not amazing" },
];

const combinedData = gardens.map((garden) => ({
  ...garden,
  feedback: feedbacks.filter((feedback) => feedback.garden_id === garden.id),
}));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a type mismatch error in Typescript while working with Redux state in a store file

It appears that I have correctly identified all the types, but could there be a different type of Reducer missing? 'IinitialAssetsState' is not assignable to type 'Reducer' The complete error message: Type '(state: { assets: n ...

Substitute placeholders in the HTML code with Angular syntax

Lately, I have been encountering some issues with AngularJS. I have defined multiple scopes like this: app.controller('mainController', function($scope) { $scope.siteURL = "my website url"; }); When using the {{siteURL}} variable in ...

"Enhance Your Website's User Experience with jQuery Aut

One of the challenges I am facing involves an Ajax call that retrieves a JSON representation of data created using PHP's json_encode method: ["Montérégie","Montréal - North Shore","Montréal - South Shore"] These values are extracted from a &apos ...

Generate a div dynamically and incorporate a function that triggers on click event dynamically

In my current project, I am faced with a challenge due to laziness. My goal is to automatically generate menu buttons that are linked to different sections of a page using raw JavaScript. The issue arises when the body content of my site is loaded from an ...

How to update a dynamic list or array in Flutter using setState()?

Although I'm still new to flutter and struggling a bit with understanding state management compared to React, I've encountered some challenges in handling array variables. When attempting to setState with a different approach, I end up with unexp ...

Is it possible to eliminate all inline styles on a parent element using a child element in CSS?

I'm currently working on an Angular project and I need to remove the styling of the parent element by using the child element, based on certain conditions. It's important to note that the parent element has inline styling. My code looks somethin ...

Get the JSON array by decoding the JSON data in PHP

I have a JavaScript function that creates a JSON array and uses an AJAX post method. How should this JSON array be decoded on the PHP side? Here is my JavaScript function: var invoices = {invoice: [{ "customerName" : "John" ,"reciptionName" : "Doe" ,"dat ...

Issue with ng-selected when used alongside ng-options or ng-repeat in Angular

My application features a form where users can fill out their starting point and choose from 350 possible destinations to get directions using Google Maps. Users can select their destination by either clicking on a pin on the map or choosing from a drop-do ...

What is the best way to extract the value from a text box that is being looped through using the post method in order to insert it into

I was working with the code below. Each textbox for attendance is looped a certain number of times, and I need to capture the value of each attendance when the form is submitted to insert the values into a database. <form method="post" action="insert. ...

When scrolling the page, the Circle Mouse Follow feature will dynamically move with your cursor

Hey everyone! I'm currently working on implementing a mouse follow effect, but I'm facing an issue where the circle I've created moves along with the page when scrolling, instead of staying fixed to the mouse. Any suggestions or tips would b ...

CSS Attribute Selector Wildcard Capture Tool

Suppose I have the following HTML structure: <div class="tocolor-red"> tocolor </div> <div class="tocolor-blue"> tocolor </div> <div class="tocolor-green"> tocolor </div> <div class="tocolor-yellow"> tocolor ...

Change the right border style for the second and third ToggleButtons in the ToggleButtonGroup

I've been working on this for a few hours now and I can't seem to get it right. Currently, I'm using Mui v5 and trying to style the ToggleButtons to look like regular MUI buttons. So far, I was able to achieve this transformation: https:/ ...

How to Stop Element Flickering While Hovering in Selenium IE Webdriver

My code is functioning perfectly in Firefox, but when I try it on Internet Explorer, there is flickering. Here is my code: WebElement mouseOver= driver.findElement(By.linkText("abc")); //I'm locating the element by link text. Selenium finds the ...

What types of data are best suited for storage in localStorage?

During the development of my social app with Vue.js and Vuex store, I am contemplating on the best practices for storing parameters in the browser's localStorage. Currently, I retain the 'token' in localStorage, but should I also store &apos ...

``There is an issue with getServerSideProps when wrapping it in a

When attempting to implement an auth handler function around getServersideProps, I encountered the following error message: TypeError: getServerSideProps is not a function The wrapper code in question is as follows: export async function protect(gssp) { ...

AngularJS gender dropdown with a default value of "empty"

I am still new to learning about angular and I am facing an issue with a dropdown menu for gender. I want to add a "--Select--" option, but it ends up duplicating. Below is the code snippet: <td style="font-family: Brandon-Grotesque, Helvetica Neu ...

What is the reason for AngularJS not invoking the said function?

I need to trigger a function when the app starts in order to display a modal. I have attempted to do this by... The function is invoked using the onDeviceReady event. document.addEventListener("deviceready", onDeviceReady, false); function onDeviceR ...

What is the best way to initiate an event from a control within a GridView?

I need help with triggering an event to reset the text of a label. Within my GridView, I have a row defined like so: <asp:TextBox ID="txtgvEmailAddress" Text = '<%# Eval("EMAIL")%>' runat="server" Width="200px" onclick="ResetMessage()" ...

Using jQuery to dynamically disable links based on their HTML content

I am looking for a way to disable links based on the content within their HTML tags. In my website, there are several classified sections that may not always have content filled out. My goal is to visibly indicate to viewers when a classified section is em ...

Concerns with textbox placement while scrolling with an absolute position style

I have an ASP:textbox on a page with various controls and divs, where I am setting the style to position:absolute on the "onkeyup" event. The height of the textbox increases dynamically based on the characters entered, but the issue is that the textbox alw ...