var graph= {
node: [
{ id:"A",
name:"A"
},
{ id:"B",
name:"B"
}
]
}
var yourInput = document.getElementById("vertext").value
// The user inputs A or B..
var convertToInt = graph.node.indexOf(yourInput)+1;
// I am always getting 0 ..
My solution: I looped through graph node object and check the indexOf the input if is A, B..and then convert the user input to integer value based on IndexOf alphabet present in object array.
Please can somebody explain what am I doing wrong here..?
Because you want to check a value against a property of each of your array elements, Array.findIndex is the appropriate tool instead of Array.indexOf.
var convertToInt = graph.node.findIndex(e => e.id == yourInput) + 1;
The inner function checks the id property of each of the array elements against yourInput. You could easily modify it to check the name property instead, or do just about any comparison you can think of.
var graph = {
node: [{
id: "A",
name: "A"
},
{
id: "B",
name: "B"
}
]
}
document.getElementById("vertext").onchange = function() {
var yourInput = document.getElementById("vertext").value
// The user inputs A or B..
var convertToInt = graph.node.findIndex(e => e.id == yourInput) + 1;
document.getElementById("output").textContent = convertToInt;
};
<select id="vertext">
<option value=""></option>
<option value="A">A</option>
<option value="B">B</option>
</select>
<br>
Index is <span id="output"><span>