1

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} ...
2
  • Are you asking for an array of objects as the output? [{id: 'abc', val: 12}, {id: 'abc', val: 1} ...] - and do you want to split exactly on three characters, or perhaps split based on letters versus digits? Commented Jun 2, 2012 at 7:40
  • yeah letters vs digits would be much better if can show me ? :) Commented Jun 2, 2012 at 7:47

3 Answers 3

1
source.map(function(x) {
  return { id: x.substr(0,3), val: +(x.substr(3)) };
}
Sign up to request clarification or add additional context in comments.

Comments

1

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 }

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.