Andy
Andy

Reputation: 19251

Split array values to object?

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} ...

Upvotes: 1

Views: 5460

Answers (3)

gion_13
gion_13

Reputation: 41533

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 id is represented by all the characters before the first digit and the val represents the digits from the back of the string :

source.map(function(x) {
    return { 
        id: x.replace(/(^.*?)\d+$/,'$1'), 
        val: parseInt(x.replace(/^.*?(\d+)$/,'$1'),10) 
    };
});

Here's a working demo

Ps: You may want to be careful and check if the map method exists in the Array prototype 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.

Upvotes: 0

Tharabas
Tharabas

Reputation: 3422

EDIT: Not an answer to the question

This will not result in the desired mapped array, but in a single object. Sorry, misread your question :(

The answer below will return one single Object and not an array of Objects.


You can easily fold such arrays into objects with the array's reduce method:

var source = ["abc12", "abc1", "def12", "abc454"];
var obj = source.reduce(function(o, str) {
  var key = str.substr(0, 3)
  var value = parseInt(str.substr(3))
  o[key] = value;
  return o;
}, {})

// obj = { abc: 454, def: 12 }

Upvotes: 1

user1046334
user1046334

Reputation:

source.map(function(x) {
  return { id: x.substr(0,3), val: +(x.substr(3)) };
}

Upvotes: 1

Related Questions