2

I found in the docs that you can create an plain object like this:

var y = {
  name: "Pete",
  age: 15
};

However, I would like to add name and value dynamically to it, for example if we have something like:

<input type="text" name="$dynamicName" id="myinput">

That I can create an object like this:

var y = {
  name: "Pete",
  $('#myinput).attr('name'): $('#myinput).val(),
};

But this will throw an error:

SyntaxError: missing : after property id

How can I use $('#myinput).attr('name') as a name of a plain object?

Scath
  • 3,777
  • 10
  • 29
  • 40
Adam
  • 25,960
  • 22
  • 158
  • 247
  • `y[$('#myinput).attr('name')] = $('#myinput).val();` – freedomn-m Jun 05 '18 at 16:25
  • Possible duplicate of [Is it possible to add dynamically named properties to JavaScript object?](https://stackoverflow.com/questions/1184123/is-it-possible-to-add-dynamically-named-properties-to-javascript-object) – freedomn-m Jun 05 '18 at 16:29

3 Answers3

4

I think this is what you are wanting to do it will add the age item to the array and then set its value to whatever is in the textbox onclick.

var y = {
  name: "Pete"  
 };
function go(){
 y[$('#myinput').attr("name")] = $('#myinput').val();
console.log(y)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"name="age" id="myinput">
<input type="button"  onclick="go(); return false;">
Scath
  • 3,777
  • 10
  • 29
  • 40
3

Try using as an Array.

Like:

y[$('#myinput').attr('name')] = $('#myinput').val();

then you can access it as a simple object.

Rohit.007
  • 3,414
  • 2
  • 21
  • 33
0

Try using:

var y = {name: "Pete"};
y[$('#myinput').attr('name')] = $('#myinput').val()];

You also have unclosed single quotes:

var y = {
    name: "Pete",
    $('#myinput').attr('name'): $('#myinput').val(),
};
Will Jones
  • 1,861
  • 13
  • 24
  • You've removed the quotes (and thus broken it) rather than add the missing one (obviously a typo) – freedomn-m Jun 05 '18 at 16:28
  • That I did, which was incredibly silly. Apologies and edited. I'd still use the first approach personally though. – Will Jones Jun 05 '18 at 16:42
  • I suspect the downvotes were because the second option doesn't work, which was the whole point of the question. First part should be ok though. – freedomn-m Jun 05 '18 at 16:51