Creating an object in real-time

Is there a way to dynamically create objects in JavaScript?

My Expectation

var tree_data = {
    'for-sale': {name: 'For Sale', type: 'folder'},
    'vehicles': {name: 'Vehicles', type: 'folder'},
    'rentals': {name: 'Rentals', type: 'folder'},
    'real-estate': {name: 'Real Estate', type: 'folder'},
    'pets': {name: 'Pets', type: 'folder'},
    'tickets': {name: 'Tickets', type: 'item'},
    'services': {name: 'Services', type: 'item'},
    'personals': {name: 'Personals', type: 'item'}
}

My Attempt

// Removed all white spaces from the string 
var name = result[index].Text.replace(/ /g, '');

// Created the item
var newMenu = {
      folder: {
           name: result[index].Text,
           type: "folder"
      }
}

// Populated the object
self.tree_data.push(newMenu);

However, my tree_data object ends up looking like this

{ 
   folder: {
         name: "For Sale',
         type: 'Folder'
   }
}

The key folder should be the same as the name without whitespace. How can I achieve this in JavaScript?

Answer №1

To access the object using the name as the index, you can do the following:

// Removing all white space from a string
var nameIndex = result[indice].Texto.replace(/ /g, ''); // Consider using .replace(/ /g, '-') instead

// Creating a new item in the menu object
var newMenu = {};
newMenu[ nameIndex ] = {
           name: result[indice].Texto,
           type: "folder"
      }
};

// Adding the new item to the json array
self.tree_data.push(newMenu);

Answer №2

tree_data is actually an object and not an array. Initialization should be done like this:

self.tree_data = {};

In order to add to it within your loop, you can use the following code snippet:

self.tree_data[nome] = novoMenu;

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

CDK Drag and Drop capability for lists within lists

I am trying to figure out how to display users and their corresponding information in a structured way. Each user should be presented in their own column, with the associated information displayed within that column. I have been attempting to drag and drop ...

Increasing the size of a div container based on the position of the cursor on the

I recently stumbled upon a fantastic website where two images slide left and right based on mouse movement. When the cursor is on the right, the right part of the image expands, and when it's on the left, the left part expands. You can check out the ...

What is the best way to create a page that moves on release using HTML/CSS?

I'm working on a website where I want to make an interactive feature. When users click on an image on the left side of the page, I want the page to move backward. Similarly, when they click on an image on the right side, I want the page to move forwar ...

Which option's value was recently removed from the fetch command?

I created a function to handle duplicate selections in a select element. It is functioning properly, but I noticed that when I remove an option from the select, my array remains unchanged. If I remove an option, I want my code to detect the value of that ...

Maintain the cache in internet browsers

Despite my efforts to prevent browser caching, the URLs of my applications are still being stored in cache. I have implemented the following code in the page load method of my master page to disable browser cache: Response.Cache.SetCacheability(HttpCachea ...

Exploring how to access properties of objects in javascript

As a novice on this platform, I'm uncertain if the title may be deceiving, but I have a question regarding the following scenario: var someObject ={} someObject.info= { name: "value" }; How can I acce ...

Looking to display the variable values on the page even after a refresh?

I am working with three variables. The first variable will receive the initial value, while the other two will get the second value. $ids = $_GET['abc']; $minprice = $_GET['minprice']; $maxprice = $_GET['maxprice']; ...

"Receiving an 'undefined index' error when attempting to post in Ajax with

Need help with sending data from client to server using AJAX in PHP. I am facing an issue when trying the following code: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script type="text/javascrip ...

Exploring the compatibility of Husky with Typicode using Yarn

Currently, I have implemented the use of husky to configure git hooks for prettier. However, I am facing a persistent issue whenever I attempt to commit or push: > husky - Can't find npm in PATH. Skipping precommit script in package.json My curre ...

Execute a function on each item within a JavaScript array

I'm working with a JavaScript array and trying to figure out how to display each item in the array within an h1 element. Can anyone help me out? This is what I have come up with so far: names = ["Jeff", "Steve", "Bill"]; function show() { let c ...

A guide to organizing page components across multiple `/pages` directories in a Next.js application

As I delve into my first project using Next.js, I find that my pages directory has expanded significantly. Now, I am keen on organizing my pages by grouping them into modules, resulting in a structure like 'src/modules/*/pages/*'. In my quest fo ...

Javascript is not fetching the value

Here is the code snippet I am working with: var categoryDetailId = $("#createEventForm-categoryDetail-idCategory").val(); and this link from my rendered page: After clicking the button, it returns NaN Update: I tried setting it manually, but it still ...

Implementing Typescript for managing state in React components

Currently, I have a state set up like this: const [newInvoice, setInvoice] = useState<InvoiceType | null>(invoice) The structure of my InvoiceType is as follows: customer_email: string customer_name: string description: string due_date: stri ...

Troubleshooting port deployment challenges on GCP for a Node.js project

My current Node.js project has one HTTP server running on port 8080, with a service URL generated for it. However, inside the http.createServer function, I have set up another server for an NLP engine that is listening on port 8081. While I am able to ac ...

Is the fs.watch method being triggered unexpectedly?

As a beginner in node.js and javascript, I've been experiencing an error with the following code snippet: fs.watch('F:/junk', (eventType, filename) => { if(filename && filename.split('.')[1].match("zip")) { ...

Mysterious dual invocation of setState function in React

My component is designed to display a list of todos like: const todosData = [ { id: 1, text: "Take out the trash", completed: true }, { id: 2, text: "Grocery shopping", completed: false }, ]; ...

ngSanitize continues to present plain text rather than rendering HTML code

When working with AngularJS scope, I encountered the need to display certain items as HTML. After some research, I realized that integrating ngSanitize was necessary for this functionality. Here is how I implemented it in my app: <script src="Scripts/a ...

The act of sending back Null from the Array.map() function

I've been attempting to retrieve data from a JavaScript object using the array.map() function. However, the result I'm receiving is null. I'm confused as to what the issue might be. Here's the object: export const Course = [ { co ...

For handling the onSubmit event, utilize both axios and axios-mock-adapter

I am attempting to utilize both axios and axios-mock-adapter in a single location to consolidate multiple mocks, then export the axios instance for use elsewhere: axios.js import axios from 'axios'; let api = axios.create({ baseURL: 'h ...

Determine the height of an element within an ng-repeat directive once the data has been fetched from an

After sending an ajax request to fetch a list of products, I use angular's ng-repeat to render them. I am attempting to retrieve the height of a div element that contains one product in the list. However, the console always displays "0" as the result ...