0

Is there a way in Javascript to generate an object , for example

function newObject(name,value) {
   // Some Awesome Logic
   return theObject
}
var test = newObject('mike',32);

And The return from new object to be an object

console.log(test); // returns an object

{
  "mike": 32
}

I need a function like this to be reusable... HELP PLEASE

5
  • That is what constructors are for. Commented Apr 3, 2017 at 21:54
  • might be just me but doesn't the constructor already create a new object each time you invoke it (reuseable)? Commented Apr 3, 2017 at 21:55
  • Given the suggestive name of the function, that seems to be what the OP wants. Commented Apr 3, 2017 at 21:57
  • i have been trying for hours, does anyone has a code example my brain is fried.. Commented Apr 3, 2017 at 21:57
  • 1
    const newObject = (k, v) => ({[k]: v}); But it's not obvious how this is better than simply using the object literal in-place. Commented Apr 3, 2017 at 21:57

2 Answers 2

3

Use the constructor pattern, with the new keyword, and the property name can be defined with [ ]:

function myObject(name,value) {
   this[name] = value;
}
var test = new myObject('mike',32);
console.log(test);

Sign up to request clarification or add additional context in comments.

Comments

1

function newObject(name, value) {
   var theObject = {};      // the plain object
   theObject[name] = value; // assign the value under the key name (read about bracket notation)
   return theObject;        // return the object
}

var test = newObject('mike', 32);

console.log(test);

In recent ECMAScript version you can do it in one line like this:

function newObject(name, value) {
  return { [name]: value }; // the key will be the value of name not "name"
}

var test = newObject('mike', 32);

console.log(test);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.