简体   繁体   中英

How to user-input an object property and key

I have in my hand, a very rare problem. I need the user to input an object's key and property.

I have an input .

<input type="text">
<input type="button" value="enter">

my js:
Take text inputed, and store it in var input .
Like for example, if user inputs "hello" then...

var myObj = {
  hello: "hello"
}

Is there a way to do that?
Thanks

Something like this?

https://jsfiddle.net/mjjLxqnr/3/

HTML:

<input type="text" id="yourInput">
<input type="button" value="Enter" id="enterBtn">

JavaScript:

var obj = {},
    enterBtn = document.getElementById('enterBtn'),
    yourInput = document.getElementById('yourInput');

enterBtn.onclick = function () {
    var input = yourInput.value;
    // Don't add anything to the obj if the input is empty.
    if(!input) return;
    // Use brackets to add a property to the obj, and set the value to be the same
    // as the property name.
    obj[input] = input;
    console.log(obj);
};

You need to use bracket notation:

If you are storing the input in a variable named input you would do this:

var myObj = {};
obj[input] = input;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM