Create a new property in Javascript using a string value as the name

Can you dynamically add properties to a JavaScript/JSON object using values from a string?

let myObj= {};

for{prop in propsToAdd){
    myObj.addProperty(prop.name, prop.type);
}

myObj.addProperty = function (name, type) {
    // need to create another JSON object 
    // with the property name as the name of the property
    // and a property called type with the value of the parameter type
}

For example:

myObj = {}
myObj.addProperty("title","string");
myObj.addProperty("id","integer")

This should result in:

myObj = {
  "title": {
    "type": "string"
  },
  "id": {
    "type": "integer"
  },
}

I am considering using JSON.stringify and JSON.parse, but I'm open to a more elegant solution.

Answer №1

If you're looking to achieve a similar result, consider using addProp on both instances instead of addProb:

const myObject = {};
// Prevent the function from being displayed when the object is printed
Object.defineProperty(myObject, 'addProp', {
  value: function addProp(key, type) {
    myObject[key] = { type };
  },
  enumerable: false
});
  
myObject.addProp("name","string");
myObject.addProp("age","integer");
console.log(myObject);

Answer №2

One option is to utilize a constructor instead of modifying the Object prototype directly:

function createObject() {
  this.addProperty = function(name, type) {
    this[name] = {type: type};
  }
}

var newObj = new createObject();

Answer №3

One way to easily assign properties to your objects is by using the brackets notation:

myObject[key] = {value: value};

let myObject = {};

myObject.addProperty = (key, value) => {
  myObject[key] = {value: value};
}

myObject.addProperty("name", "John");
myObject.addProperty("age", 30);

console.log(myObject);

Answer №4

myFunction.addProperty = function (key, value) {
   this[key] = {value: value};
}

There are two methods to add a new property to an object.

myObject.property = 'newVal';
myObject['property'] = 'newVal'

In the function above, this indicates the specific object where properties should be added.

Answer №5

Creating an object called myObj in JavaScript and adding properties to it using a custom method. The properties added are "title" with type "string" and "id" with type "integer". Finally, the custom method `addProp` is deleted and the object is logged to the console.

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

Tips for real-time editing a class or functional component in Storybook

Hey there, I am currently utilizing the storybook/react library to generate stories of my components. Everything has been going smoothly so far. I have followed the guide on https://www.learnstorybook.com/react/en/get-started and added stories on the left ...

What is the best way to leverage the Select2 plugin within Codeigniter to efficiently insert a large amount of data into my database

I am working on a PHP system using CodeIgniter, where I need to store multiple data entries in a database table through a select dropdown with the Select2 plugin. However, I'm facing an issue where only the last selected item gets stored in the databa ...

The issue of Angular's ng-repeat view not refreshing after a search query remains unresolved

Having some trouble with updating a results array in AngularJS using a service call. After submitting a form and calling the service, I set up my callbacks with .then() on the promise object. However, the view only updates when I start deleting characters ...

When extracting data, I am only receiving the initial row from the database, but I specifically require the latest row that was added in the database

I am working with a JSON data structure to fetch information from a database. However, the current implementation only retrieves the first row from the database whereas I specifically need to get the most recent row that was inserted. Here is my Java clas ...

Highcharts chart fails to expand to occupy available space

One problem I'm encountering is with a highcharts chart that does not automatically resize itself. When hidden (display: none) at page load because it's under an inactive tab, the chart only occupies half of the available space when I open the c ...

What is the method to achieve a full-width image when utilizing vertical scrollspy within Bootstrap?

Seeking a unique responsive webpage design utilizing Bootstrap. I envision a vertical scrollspy on the left paired with parallax scrolling on the right, akin to this example. Here's my current code snippet: <!DOCTYPE html> <html> <he ...

Caching of Ajax requests

I have implemented a basic javascript function to make an ajax request, which is functioning correctly. However, I have noticed that upon refreshing the page, the ajax call is triggered again. Could this issue be related to caching of the ajax call? If s ...

When using the Vue Array.splice() method, the DOM element is not removed in the element-ui table

I am facing an issue with a table containing hierarchical data in Vue. When attempting to remove a child using "array.splice", the DOM structure does not update reactively. Has anyone encountered this before? Are there any potential solutions? This proble ...

Utilizing long polling technique with jQuery/AJAX on the server end

Currently, I am facing an issue with long polling on a single page that contains multiple pages. The problem arises when a new request is made while a previous request is still processing. Even though I attempt to abort the previous request, it completes b ...

Exploring the process of retrieving parameters within a component using React Router DOM version 4

I am struggling with the following code: <BrowserRouter> <Route path="/(:filter)?" component={App} /> </BrowserRouter> In previous versions of React Router, wasn't the filter param or '' on the root supposed to be in ...

When dalekjs attempted to follow a hyperlink with text in it, the link failed to function properly

My goal is to retrieve an element from a list by clicking on a link containing specific text. Here is the HTML code snippet: <table> <td> <tr><a href='...'>I need help</a></tr> <tr><a href=&a ...

How can an array be transferred from app.get() to app.post()?

I am receiving an array from an ajax file that contains a list of products which I need to add to the order. My goal is to link the table of orderProducts and the order table together using a column called orderId. However, I am having trouble getting the ...

Using Angular's Jasmine SpyOn function to handle errors in $resource calls

I need to write unit tests for an AngularJS service that utilizes $resource. I want to keep it isolated by using Jasmine's spyOn to spy on the query() method of $resource. In my controller, I prefer to use the shorter form of query() where you pass su ...

Tips for displaying a Rails action without a layout in html format using Ajax

Is it possible to render the new action without the application layout and without altering the current code structure? class FoobarController < ApplicationController def new @foobar = Foobar.new end # ... end When a user clicks on = link_ ...

What are some ways to render a React component when its ID is only determined after making an AJAX call?

Currently, I am working on developing a chat application where a chat message is immediately displayed (using a React component) once the user sends it by hitting the Enter key: https://i.sstatic.net/MJXLd.png https://i.sstatic.net/S6thO.png As shown in ...

Combine several forms into a single submission

On the webpage, I am faced with the challenge of having two separate forms that need to function as one cohesive unit for the user. Despite my efforts to reuse code and integrate elements seamlessly, I am unable to consolidate the two forms into a single e ...

Issue with DateTime picker functionality not functioning as expected

My MVC5 project is having trouble with adding a date picker. I keep getting an error in the JS code and I'm not sure what I'm missing. I tried adding Nuget for datetime picker but it's still not working. The console error is: Uncaught TypeE ...

Modify the height of React Cards without implementing collapse functionality

Currently, I am in the process of developing a web interface that displays various processes and services. The information is presented in React cards that support expand/collapse functionality. However, I am facing an issue where expanding one card affect ...

How can you identify a "422 Unprocessable Entity" error using JSON response in Laravel?

Currently, I am working on retrieving the server's response. In case the server responds with a 422 Unprocessable Entity status code, I aim to adapt my function to provide different responses for users. There are two potential errors that may occur: ...

Tips for using Jackson to deserialize a JSON file containing changing keys

I have a JSON formatted string with random number keys. { "tasks": { "0": { "key1": "value1" }, "100": { "key1": "value2" } } Is there a way to convert this JSON string into a Java object using the Jackson library? What shou ...