How can I automatically fill a vacant value in an array object with a matching object from another array using JavaScript?

Can anyone provide me with some guidance on how to automatically fill in empty table fields based on previous information? I'm struggling to figure it out and would appreciate any ideas.

Below is an example of two arrays: one with fruits and the other with the desired answer to be applied if there is a match.

//I am attempting to populate the 'doYouLike' field

const CheckingFruits = () => {
  var fruits = [
    { name: 'orange', color: 'orange', doYouLike: '' },
    { name: 'banana', color: 'yellow', doYouLike: '' },
    { name: 'pinneaple', color: 'yellow', doYouLike: '' },
    { name: 'apple', color: 'red', doYouLike: '' },
  ];

//I want to fill in this information based on logic that I am unsure of
   const doILke = [
    { name: 'orange', answer: 'yes' },
    { name: 'banana', answer: 'no' },
    { name: 'pinneaple', answer: 'no' },
    { name: 'apple', answer: 'yes' },
  ];

  return (
    <table>
      <thead>
        <tr>
          <th>Name</th>
          <th>Color</th>
          <th>Do you like?</th>
        </tr>
      </thead>
      <tbody>
        {fruits.map((fruit, id) => (
          <tr key={id}>
            <td>{fruit.name}</td>
            <td>{fruit.color}</td>
      //I would like to display the answer here
            <td>{fruit.doYouLike}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
};

CheckingFruits()

I have been searching for an answer on YouTube and forums for several days with no luck.

I recently learned how to find a single value:

function filterByOneFruit(fruit, fruitName) {
    return fruit.filter((item) => item.name === name);

const foundTheFruit= filterByOneFruit(
    fruits,'apple'
);

//Output: { name: 'apple', color: 'red', doYouLike: '' }

However, I am unsure how to find and modify multiple values simultaneously.

Your help would be greatly appreciated.

Answer №1

const fruits = [{
    name: 'orange',
    color: 'orange',
    doYouLike: ''
  },
  {
    name: 'banana',
    color: 'yellow',
    doYouLike: ''
  },
  {
    name: 'pinneaple',
    color: 'yellow',
    doYouLike: ''
  },
  {
    name: 'apple',
    color: 'red',
    doYouLike: ''
  },
];

const doILike = [{
    name: 'orange',
    answer: 'yes'
  },
  {
    name: 'banana',
    answer: 'no'
  },
  {
    name: 'pinneaple',
    answer: 'no'
  },
  {
    name: 'apple',
    answer: 'yes'
  },
];

fruits.forEach((fruit) => {
  const foundFruit = doILike.find((item) => item.name === fruit.name);
  if (foundFruit) {
    fruit.doYouLike = foundFruit.answer;
  }
});

const tableBody = document.querySelector('#fruitTable tbody'); // get table body


fruits.forEach((fruit) => {
  const row = document.createElement('tr'); //Create table rows for each fruit

  const nameCell = document.createElement('td');
  nameCell.textContent = fruit.name;
  row.appendChild(nameCell);

  const colorCell = document.createElement('td');
  colorCell.textContent = fruit.color; // set fruit color
  row.appendChild(colorCell);

  const likeCell = document.createElement('td');
  likeCell.textContent = fruit.doYouLike; // set fruit doYouLike
  row.appendChild(likeCell);

  tableBody.appendChild(row); // add row to body
});
body {
  font-family: Arial, sans-serif;
  margin: 20px;
}

h1 {
  text-align: center;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin: 20px 0;
}

th,
td {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

th {
  background-color: #f2f2f2;
}

tr:nth-child(even) {
  background-color: #f9f9f9;
}

tr:hover {
  background-color: #f1f1f1;
}
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

<body>
  <h1>Fruit </h1>
  <table id="fruitTable">
    <thead>
      <tr>
        <th>Name</th>
        <th>Color</th>
        <th>Do you like?</th>
      </tr>
    </thead>
    <tbody>
    </tbody>
  </table>
</body>

</html>

Answer №2

Iterate through the array of fruits. For each fruit, look for a matching fruit in the doILike array and transfer its answer value.

var fruits = [
    { name: 'grape', color: 'purple', doYouLike: '' },
    { name: 'kiwi', color: 'green', doYouLike: '' },
    { name: 'watermelon', color: 'pink', doYouLike: '' },
    { name: 'pear', color: 'green', doYouLike: '' },
  ];

//Using this information, I aim to complete the task, however, the process is still unclear to me
const doILike = [
    { name: 'grape', answer: 'yes' },
    { name: 'kiwi', answer: 'no' },
    { name: 'watermelon', answer: 'no' },
    { name: 'pear', answer: 'yes' },
  ];
  
fruits.forEach(future => 
    future.doYouLike = doILike.find(like => like.name == future.name)?.answer || ''
);

console.log(fruits);

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

Preventing an iframe from reloading when transferring it to a new parent using appendChild

I'm looking to relocate an iframe to a different parent element while maintaining the iframe's current state (including scroll position and any entered form data). Unfortunately, when I use appendChild() to move the iframe, it reloads and resets ...

Adding a file attachment and preview feature within a text area: a step-by-step guide

I have been working on a chat box that includes emojis and a file attachment button. While the emojis are functioning correctly, I am experiencing difficulty with the file attachment preview not showing in the text area. Are there any suggestions or plugin ...

How to retrieve the value of an element within a facebox div with jquery

On my page, I have two div tags displayed below. Whenever I try to retrieve the value of the itemName element using $('#itemName').val();, it always returns the value of the element in the first div (which is blank). Is there a way to access the ...

Ways to remove unnecessary div containers in Nuxt js?

This is an example of my page: https://i.sstatic.net/CYCRL.png Showing the Nuxt layout: <template> <div> <Nuxt /> </div> </template> After being compiled by Nuxt, it generates: https://i.sstatic.net/CYdX3.png You ...

Unexpected server failure when connecting via socket.io to Node.js http-proxy

I'm encountering an issue with my Nodejs proxy server related to the dreaded socket hang up error. The server crashes every time I refresh the browser on 'app.example.com'. The connection seems fine and the page loads correctly, but the cra ...

Having trouble with AES decryption on my nodeJS/ExpressJS server backend

Looking to decipher data post retrieval from mongoDb. The retrieved data comprises encrypted and unencrypted sections. app.get("/receive", async (req, res) => { try { const data = await UploadData.find(); const decryptedData = data. ...

Invoke a Java script function for Regular Expression validation failure in ASP.NET

I have a <asp:RegularExpressionValidator> that validates a text box, and I also have a JavaScript function that prevents entering non-numerical values in the textbox. When I use the expression validator alone, it works fine. However, as soon as I add ...

The unit argument provided for Intl.NumberFormat() is not valid for electrical units such as volts and joules

After attempting to localize my web application, I have run into an issue with Intl.NumberFormat not working properly with electric units such as ampere, ohm, volt, and joule. The documentation provides examples and a list of available units. Despite fol ...

How to connect an external module to NuxtJS using Vue.js

Attempting to incorporate a widget/plugin/extension system into my existing web UI built with NuxtJS. Within the pages/view.vue single-file component, I aim to establish the extension system by dynamically loading components indicated through query paramet ...

Can you explain the concept of asynchronous in the context of Ajax?

Can you explain the concept of Asynchronous in Ajax? Additionally, how does Ajax determine when to retrieve data without constantly polling the server? ...

What is the best way to create a JavaScript Up/Down Numeric input box using jQuery?

So, I have this Numeric input box with Up/Down buttons: HTML Markup: <div class="rotatortextbox"> <asp:TextBox ID="txtrunningtimeforfirstlot" ClientIDMode="Static" runat="server">0</asp:TextBox> (In mins) </div> <div cl ...

What is the functionality of Vue plugins in Vite MPAs?

I have developed a Vite application and I am trying to implement multiple pages. I followed the documentation on how to achieve this (link here), but when I start the server, all I see is a blank page. This is what my vite.config.js file looks like: impor ...

Creating a custom backdrop for your kaboom.js webpage

I created a kaboom.js application and I'm having trouble setting a background for it. I've searched online extensively and attempted different methods on my own, but nothing seems to be working. (StackOverflow flagged my post as mostly code so I ...

Interacting between various components in separate files using React.js

Creating a page using React involves two Components with different functions. The first component, ProfileFill, is responsible for capturing form data. On the other hand, the second component, ProfileFillPercent, which resides in a separate file, calculate ...

Adjust hover effects based on true conditions

Currently working on a web app using HTML, CSS, JavaScript, and AngularJS. Progress so far includes a clickable box that triggers a javascript function to display more boxes upon click using ng-click. <div ng-click="!(clickEnabled)||myFunction(app)" cl ...

Efficiently bundling Angular templates using Grunt and Browserify

I am currently utilizing angular1 in conjunction with browserify and grunt to construct my application. At present, browserify only bundles the controllers and retrieves the templates using ng-include through a separate ajax call. Due to the excessive amo ...

What is the most straightforward method to convert a current Express node app into a static site?

After primarily working with React and create-react-app, I've grown accustomed to the convenience of having a build utility for npm that simplifies deploying projects to static web hosting platforms like github pages or surge. This process ultimately ...

Examining REST API functionality through the use of a Console, requiring an integer list as a parameter

Currently, I am in the process of testing a REST API to perform an action that requires a list of integers. I am uncertain about how to correctly handle the parameters required for this test. In my request payload, I have included the following: idAttac ...

Having trouble sending values via POST request in Node.js using Express

Currently, I am in the process of learning how to use Express (v4) with Node.js. My main goal right now is to create a basic REST API. This API specifically focuses on one endpoint: /orders. The main functionality I am trying to achieve is the ability to r ...

Tips for Setting Up Next.js 13 Route Handlers to Incorporate a Streaming API Endpoint via LangChain

I am currently working on establishing an API endpoint using the latest Route Handler feature in Nextjs 13. This particular API utilizes LangChain and streams the response directly to the frontend. When interacting with the OpenAI wrapper class, I make sur ...