Search code examples
javascriptprompt

How can the result of the input from the cycle be saved to the object?


How to change cycle, that input will be saved in object like this:

expenses: {
    “Item name[1]” : “Item price[1]”,
    “Item name[2]” : “Item price[2]”
}

Here is the code:

let appData = {
    expenses: {},
    value: 0,
    askExpenses: {},
    asking: function() {
        for (let i=0; i < 2; i++) {
            appData.askExpenses[i] = prompt('item name');
            appData.value[i] = +prompt('item value');
            }
    }
};
appData.asking();

Solution

  • You can use the title as the key by wrapping the variable in brackets.

    let appData = {
      expenses: {},
      value: 0,
      askExpenses: {},
      asking: function() {
        for (let i = 0; i < 2; i++) {
          title = prompt('item name');
          value = +prompt('item value');
          appData.expenses[[title]] = value;
        }
      }
    };
    appData.asking();
    
    console.log(appData.expenses);