Sam B. Sam B. - 3 months ago 10
Javascript Question

Pushing data into object clears the other values

I'm making trying to push data into an object, but as soon as I push data to

userID.name
, the value of
userID.age
gets reset(?) in the console. Here's my code:

if (input.indexOf("ben") >= 0){
var slot = splitInput.indexOf("ben");
console.log(slot)
i = slot + 1;

if (splitInput[i].indexOf(0) >= 0 || splitInput[i].indexOf(1) >= 0 || splitInput[i].indexOf(3) >= 0 || splitInput[i].indexOf(4) >= 0 || splitInput[i].indexOf(4) >= 0 || splitInput[i].indexOf(5) >= 0 || splitInput[i].indexOf(6) >= 0 || splitInput[i].indexOf(7) >= 0 || splitInput[i].indexOf(8) >= 0 || splitInput[i].indexOf(9) >= 0){
i = 0;
var slot = splitInput.indexOf("ben");
// console.log(slot)
i = slot + 1;
userID.age = splitInput[i];
console.log(userID);

} if (splitInput[i].indexOf("a") >= 0 || splitInput[i].indexOf("e") >= 0 || splitInput[i].indexOf("i") >= 0 || splitInput[i].indexOf("u") >= 0){
i = 0;
var slot = splitInput.indexOf("ben");
// console.log(slot)
i = slot + 1;
userID.name = splitInput[i];
console.log(userID);
}
}


Here's my
splitInput
:

var splitInput = input.split(" ");


input is gathered through a
getElementById
function.

When I manually log
userID
I get this error
VM935:1 Uncaught ReferenceError: userID is not defined(…)
which may have something to do with it, although
console.log(userID)
works fine.

If you need more information, please let me know.

Thanks in advance!

Answer

Before assigning to an object property, like UserID.age, you must first have defined UserID itself.

So put this before you access a property of UserID:

var userID = {};

Remarks on the code

The way you check for numbers and words with vowels is not really that nice. It has a lot of repetitive code. Also inside the if blocks you were searching again for the word "ben", while you had that already done... Seems unnecessary to do that again.

Have a look at this version of your code:

// Sample data
var input = 'ik ben 51 jaar';

var splitInput = input.split(" ");
// This was missing:
var userID = {};
// Move retrieval of slot before the `if` so it can be reused
var slot = splitInput.indexOf("ben");
if (slot >= 0){
    console.log('slot:', slot);
    i = slot + 1;
    // Make sure you are not at the end of the array, and 
    // use a regular expression to see next word consists of digits only
    if (i < splitInput.length && splitInput[i].match(/^\d+$/)){
        // convert the word to number with unitary plus:
        userID.age = +splitInput[i];
    } 
    // You'll maybe want to do an else here.
    // Use regular expression again; don't forget the "o"
    else if (i < splitInput.length && splitInput[i].match(/a|e|i|o|u/)){
        userID.name = splitInput[i];
    }
    console.log(userID);
}

Comments