Using JavaScript to assign unique values to properties in an object array and display them as an HTML table

Objective: My goal is to work with a list of n strings, assign them referential values, and display them as rows in an HTML table.

--- Overview ---

Firstly, I will start with a list of n strings:

'object1'
'object2'
'object3'
...etc.

Next, I aim to match these strings with other data obtained through API calls to determine their properties:

name: 'object1', id: 00112233, count: 25,
name: 'object2', id: 266924, count: 12884,
name: 'object3', id: 312011045, count: 8,
...etc.

Lastly, my plan involves rendering these objects and their properties in a table consisting of n rows on a website:

  Name  |    ID     |  Count  |
--------|-----------|---------|
object1 | 00112233  | 25      |
object2 | 266924    | 12884   |
object3 | 312011045 | 8       |
...etc. | ...etc.   | ...etc. |

--- My Approach ---

To begin, I consider storing the original list of n strings as an array:

array = [
  'object1'
  'object2'
  'object3'
  //...etc.
]

I then use this array to create n objects within another array:

objArray = array.map(e => {
    return{name: e};
});

Subsequently, I iterate through this array of objects to add properties and specific values:

for (let i = 0; i <= objArray.length; i++) {
  objArray[i].id = <id value from API corresponding to each object name>;
  objArray[i].count = <count value from API corresponding to each object name>;
}

The hope is to achieve a structure like this that can be inserted into an HTML table or similar:

objArray = [
  {name: 'object1', id: 00112233, count: 25},
  {name: 'object2', id: 266924, count: 12884},
  {name: 'object3', id: 312011045, count: 8},
  //etc...
]

--- TLDR ---

Objective: Transform a list of n strings into HTML table rows with associated referential values.

  • Seeking feedback on the efficiency of my methodology and if there's room for improvement.
  • Exploring techniques to loop through objects in an array and add diverse properties individually.
  • Determining the process to inject an array of objects into an HTML table effectively.

Thank you for your assistance! It's my first question here, so any guidance on proper etiquette would be appreciated.

Answer №1

Hey there, it's me, the original poster! If you happen to stumble upon this discussion, let me share my experience with solving a particular coding dilemma. It turned out that I was making things more complicated than they needed to be by trying to follow a certain step. In reality, a much simpler approach existed:


The solution involved utilizing an array to generate multiple objects nested within another array:

objArray = array.map(e => {
    return{name: e};
});

Instead of persisting with mapping the string array to an object, I opted to directly insert the API results into the array using the following technique:

for (let i = 0; i < stringList.length; i++) {
    $.ajax({
        'url': <api url> ,
        'headers': <api headers> ,
        'success': function (functionObj2) {
            objArray.push({
                "name": <name from api>,
                "count": <count from api>
            });
        }
    });
}

The core issue stemmed from mistakenly handling the objArray.push segment, leading to data being overwritten. Initially, I attributed this problem to regular JavaScript errors before realizing it was actually occurring within my AJAX implementation.

Answer №2

  1. effective method for organizing thoughts can appear

    <div id="tablebelow">
    </div>
    
    var itemsArray =  [
     {title: 'item1', code: 00112233, quantity: 25},
     {title: 'item2', code: 266924, quantity: 12884},
     {title: 'item3', code: 312011045, quantity: 8}
    ]
    
    var tablecontent = "<table><tr><th></th> <th>Title </th><th>Code</th><th>Quantity </th></tr>" ; 
    $.each(itemsArray,function(key,value){
          tablecontent  += "<tr><td>"+ value.title + "</td>" ; 
          tablecontent  +="<td>"+value.code + "</td>" ; 
          tablecontent +=  "<td>"+ value.quantity + "</td></tr>" ;
    });
    
    $("#tablebelow").html(tablecontent);
    

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

Searching and updating an element within an array while also inserting a new key in JavaScript

My goal is to add a key to an Object of Array as isActive: true. I then need to locate the object in the actual array with the same label as that of selectedFilterList and replace it in this.bindingData, or add isActive: false if it doesn't exist. if ...

What is the optimal strategy for incorporating both useLazyQuery and useQuery within the Apollo-client based on specific conditions?

In the navigation menu, I have options for "foods" and "cakes." The Foods page displays a list of all food items url: /foods When the user clicks on cakes, they are redirected to /foods?food=cakes, which is essentially the same page as the foods above. ...

Struggling to send an object through a node route for rendering a page?

Currently tackling a node.js project using express.js. I have a route that renders an ejs page and passes along the team object. Strangely, when I try to access <%= team.member.name %>, it returns as undefined despite the information being present. A ...

What is the best way to delay the loading of a JavaScript script on my website for 20 or 30 seconds

Is there a way to load the following JavaScript ad after 30 seconds on my WordPress site? <script type="text/javascript"> var uid = '219412'; var wid = '586053'; var pop_tag = document.createElement('script ...

Error encountered when uploading mp3 file to S3 node due to size limitation

Currently, I am utilizing Node to transmit mp3 files to Amazon S3. However, after uploading the file, it shows a size of 9.0 Bytes and when attempting to play the audio from the public URL, it does not work as expected. Here is my current code snippet: rou ...

Retrieving JSON data by key through ajax does not show the expected output

I'm currently working with JSON data in the form of an array, and I'm facing some issues. Here's how the data looks: [ { "id": 1, "name": "Leanne Graham", "username": "Bret", ...

Setting up StrongLoop LoopBack MongoDB datasource for successful deployment on Heroku

Currently, I am utilizing LoopBack version 1.6 and have a local mongoDB server operational for development purposes with the following datasource configuration: "mongodb": { "defaultForType": "mongodb", "connector": "loopback-connector-mongodb", ...

JavaScript code for sending information to the server

I am attempting to write data to a file on the server when a user clicks on a button, using JavaScript. I followed the method outlined in this Stack Overflow post: Saving a text file on server using JavaScript. Unfortunately, it did not work as expected. ...

How can I efficiently make a dropdown menu with search functionality instead of using datalist?

I am currently working on creating a custom searchable input field that makes backend calls. Instead of using datalist, I want to design a unique UI with ul and li items. While I have successfully implemented the search functionality, I am facing a glitc ...

Oops! You forgot to include the necessary getStaticPaths function for dynamic SSG pages on '/blogs/[post]'

Whenever I attempt to execute npm run build, an error occurs. The following build error occurred: Error: getStaticPaths is required for dynamic SSG pages and is missing for '/blogs/[post]'. This is the code snippet causing the issue: function ...

Discover the indexes within an array that include any of the values from a separate array

Is there a way to determine the indices of values within an array (a) that correspond to elements in another array (label) which contains multiple "markers"? For instance, consider the following: label = array([1, 2]) a = array([1, 1, 2, 2, 3, 3]) The ob ...

Having issues with TableExport.js exporting Bootstrap HTML tables

I've been trying to use the TableExport.js plugin found at to add Bootstrap HTML table export functionality to my website. I meticulously followed all the steps to include jquery FileSaver, tableExport javascripts, and css. <!-- jQuery --> &l ...

What is the process for closing the side menu by clicking on the dark area?

I created a basic side navigation menu. When you resize the window to a smaller size, a red square will appear. If you click on this red square, the menu will open. The menu opens correctly, but I want it to close when I click on the dark area instead of ...

Clearing a textarea in jQuery that is populated with text

Having an interesting dilemma. I'm trying to clear a <textarea> and then replace it with new content. The functions in the JSFiddle will work perfectly fine if the textarea is left empty, but as soon as any text is manually typed into it, the me ...

What is the best way to pass multiple variables to PHP through an AngularJS Ajax request?

Currently, I am in the process of learning AngularJS and I am curious about how I can send multiple data variables through Angular AJAX, similar to how I would accomplish this task using jQuery. Using jQuery, I have previously achieved this like so: $.po ...

Why isn't the PHP snack bar working when clicking on an href <a> using onClick?

How can I dismiss this snackbar when the add to cart <a href> is clicked? I've tried but nothing seems to work. Can anyone provide some assistance? Here is my code: SNACKBAR CODE <div id="snackbar">Some text some message..</div> A ...

Using AJAX with the GET method, send a form submission to retrieve a response using XMLHTTPRequest

I am working on a form where users can select values from two dropdown menus. The options in the dropdowns are populated dynamically from a JavaScript file, which contains a list of exchange rates. I have written the code to calculate and display the resul ...

Upgrade button-group to dropdown on small screens using Bootstrap 4

I am currently developing a web application and incorporating Bootstrap 4 for certain components such as forms and tables. Within the design, I have included buttons grouped together to display various actions. Below is an example code snippet: <li ...

What is the reason for $addToSet always returning 1 upon update?

Recently, I have been utilizing mongoose for my project. I encountered an issue when attempting to update my data in a specific way. model.update({_id: id}, {$addToSet: {refs: refId}}, function(err, numAffected){ console.log(numAffected); }) Although t ...

Suggestions for converting an array-like sequence into an associative map?

Is there a concise way to achieve the equivalent of this Python function in JavaScript? def to_dict(coll, key): return {i[key]: i for i in coll} assert to_dict([ {'key': 1, 'value': 1}, {'key': 2, 'value&apo ...