I was wondering how to convert an array to an object by splitting the values ?
var obj = {
id: '',
val: ''
}
By this I mean – if I have an array like
["abc12", "abc1", "def12", "abc454"]
How I could split the first 3 values off – so it end up like an object like:
{id: 'abc', val: 12}, {id: 'abc', val: 1} ...
One solution is to map your array (like herby noted) with a function that converts an element of your array to an object of your desired form.
In this case, the
idis represented by all the characters before the first digit and thevalrepresents the digits from the back of the string :Here’s a working demo
Ps: You may want to be careful and check if the
mapmethod exists in theArrayprototype chain, because older browsers may not have this implemented. Here’s a link that explains how to cover this browser incompatibility : http://www.tutorialspoint.com/javascript/array_map.htm.