"Inserting" a fresh key-value pair into a JavaScript Object

I know that with arrays, only array elements can be added using the .push() method.

My goal is to achieve a similar functionality for objects.

I am familiar with both dot and bracket notation, so this is not a basic question for me. However, I need to do it dynamically in a loop using variables.

I have tried looking into Object.assign() but I couldn't get it to work as intended.

The function below gets called repeatedly. It's essential to normalize the data provided to the function into a mini database using a JavaScript object.

The issue lies in the last line where divContent[section].items[idValue] keeps getting overwritten.

How can I make it so that the record object is "pushed" into the key represented by items[idValue]?

I expect to achieve { itemsKey: { k1:v1, k2:v2, k3:v3 } }. Thank you!

The order of the items does not matter. They should be accessible later on as itemsKey[k1], for instance.

  function createItemDb (section, fileName, fileContent) {
    var fileExt = fileName.split('.')[1].toLowerCase();
    fileType = ((fileExt == 'caption') || (fileExt == 'url')) ? fileExt : 'img';
    if (fileType == 'img') {
      var regExp = /\((.*?)\)/g;
      var matches = regExp.exec(fileName);
      fileType = matches[1].toLowerCase();
    }
    var regRemoveParenIncl = /\([^)]*\)/;
    var regRemoveExt = /\.[^\/.]+$/;
    var idValue = fileName.replace(regRemoveParenIncl,'').replace(regRemoveExt,'');
    
    record = {};
    record[fileType] = fileName;
    
    divContent[section].items[idValue] = record;
  }

Answer №1

If you're looking for a data structure that allows both index-based and key-based access, unfortunately, such a structure does not exist in standard libraries. One workaround is to create a custom object that contains both an Array and an Object, then implement functions to handle storage and retrieval using different parameters for indexing.

You might find this Stack Overflow thread helpful: How to access non-numeric object properties by index?

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

Exploring ways to utilize array.find by comparing it to a different object

There are two arrays in JavaScript named designs and articles. var designs = [ { design_id:"bwbmbqlujurv", article_id:14782, name:"adidas demogorgon black" }, { design_id:"lg9yba2gkcwr", article_id:14782, name:"harry potter w ...

Are you experiencing issues with the map displaying inaccurate latitude and longitude when clicking on a specific point?

I've successfully created a simple polyline on Google Maps and attached a click event listener to it. However, I'm encountering an issue where clicking on the line provides me with latitude and longitude coordinates that point to Canada, even th ...

Tips for speeding up page loading when using the same image multiple times on a page

Is it possible to utilize a JavaScript Image object? If yes, could you provide an illustrative example? And is it feasible to achieve this with jQuery? ...

The web method within the aspx page is failing to execute

On page load, I am attempting to make an ajax request using the AngularJS $http service to fetch JSON data from a web method located in my User.aspx.cs page. The web method is defined as follows: [WebMethod] [ScriptMethod(ResponseFormat=ResponseForma ...

The width and height properties in the element's style are not functioning as expected

let divElement = document.createElement("div"); divElement.style.width = 400; divElement.style.height = 400; divElement.style.backgroundColor = "red"; // num : 1 divElement.innerText = "Hello World "; // num : 2 document.body.append(divElement); // Af ...

Convert the text inside a span element into a key-value object in JavaScript

How can I extract and save the text from a span element as key value pairs within a div? <div class="data-diff-span__composite-list-item__18c5zip data-diff-core__highlight-area__19c0zip"> <div class="data-diff-basic__class-row__4n ...

Tips for automatically filling in fields when a button is clicked in a React application

I'm attempting to pre-fill the form fields that are duplicated with data from already filled fields. When I click the "Add Fields" button, new fields are replicated, but I want them to be pre-populated with data from existing fields. How can I access ...

Find the total number of duplicate elements in a JavaScript array

I'm using an ajax call to retrieve values from a JSON structure and pushing them into a JavaScript array with .push for each iteration. However, I have multiple instances of the same value (e.g. person's name) in the array and I want to count the ...

Unable to append HTML table row to designated table

I am trying to populate an HTML table with the JSON string data I receive. The object data seems correct, but for some reason, it is not getting appended to the table. Can you help me identify what's wrong with my jQuery append statement? functio ...

Having issues with using the class selector in SVG.select() method of the svg.js library when working with TypeScript

Exploring the capabilities of the svg.js library with typescript has presented some challenges when it comes to utilizing CSS selectors. My goal is to select an SVG element using the select() method with a class selector. In this interactive example, this ...

Ways to stop a webpage from auto-refreshing using JAVASCRIPT

While working on a form to submit values using AJAX and PHP, I encountered an issue where the return value of AJAX was always 0. After some investigation, I realized that the problem was caused by the page being refreshed. AJAX var xhttp = new XMLHttpRequ ...

When a user connects to Node.js using sockets, the previous messages are loaded. However, a bug causes the messages to be loaded to all chat users, instead of just the

New to node.js, I am currently creating a chat application with two main files: server.js (server side) and script.js (client side). In the server.js file: socket.on('previousMessages', function (data){ db.query("SELECT * FROM messages", f ...

Struggling with date validation as a new MomentJS user

Looking to validate a date in string format using moment JS, I am encountering an issue. Using the dd/mm/yy format in pCalendar in ngPrime, I store the date value in stDate. Here is the code I have written: var stDate = '02/02/2021'; var stDate ...

When attempting to incorporate Jasmine into my current AngularJS/Bootstrap project, I encountered the error message stating

Currently, I am working on a group project that requires test coverage. The project utilizes npm and angularJS. To kick things off, I performed an npm install for jquery, jasmine, and angular-mocks. Since I'm relatively new to testing, I decided to st ...

The LatinSquare.js script has exceeded the maximum call stack size limit

In my current project, I am utilizing the latin-square library for node.js within a loop to search for a specific pattern. However, I encountered an error after running the script for 2 minutes: RangeError: Maximum call stack size exceeded var latin ...

Remove any current query parameters from the Angular UI Router when navigating to the same route

I am currently using angular ui router to navigate between different pages and I have a route that includes multiple query parameters. The issue I am encountering is that when I switch routes for the same page with new query parameters, the existing parame ...

Tips on deactivating a button after it has been clicked once within a 24-hour period and reactivating it the following day with the use of JavaScript and Angular

Is it possible to disable my button after one click per day, and then automatically re-enable it the next day once a user has entered details using the submit button? I need assistance with JavaScript or AngularJS for this functionality. ...

Converting Vue HTML to PDF without relying on html2canvas functionality

My current challenge involves creating a PDF file from either HTML or Vue component. I have experimented with various libraries such as jsPDF, html2pdf, and vue-html2pdf, but it seems like they all rely on html2canvas, causing the UI to freeze for a few ...

Running Jasmine asynchronously in a SystemJS and TypeScript setup

I am currently executing Jasmine tests within a SystemJS and Typescript environment (essentially a plunk setup that is designed to be an Angular 2 testing platform). Jasmine is being deliberately utilized as a global library, rather than being imported vi ...

Issue 404: Trouble sending form data from React to Express

I'm facing an issue when trying to send form data from a React frontend to my Node.js/Express backend. The problem seems to be related to a 404 error. I've included only the relevant code snippets below for reference. Function for submitting the ...