loretoparisi
loretoparisi

Reputation: 16271

php array concat in javascript

I have a string of numbers separated by : like "20:1:21,21:0:21", this php code explodes the strings with , and and concatenate the resulting arrays into an associative array like:

$in = "20:1:21,21:0:21";
$list=explode(",",$in);
$results = array( 0 => array(), 1 => array());
foreach ($list as $item) {
        $item=explode(":",$item);
        if (sizeof($item)==3) {
            $results[$item[1]][$item[0]] += $item[2];
        }
    }

note the += operator here.

The expected value of

array(2) {
  [0]=>
  array(1) {
    [21]=>
    int(21)
  }
  [1]=>
  array(1) {
    [20]=>
    int(21)
  }
}

or [{"21":21},{"20":21}] as json output.

In javascript it could be like

    var results = { 0: [], 1: [] };
    for (var key in list) {
        var item = list[key];
        item=item.split(":");
        if (item.length == 3) {
            if(!results[item[1]]) results[item[1]]={};
            results[item[1]][item[0]]=item[2];
        }
    }

but it creates a list of null values before appending the right values, why?

Upvotes: 0

Views: 239

Answers (2)

Mihai Matei
Mihai Matei

Reputation: 24276

Or you can use Regex to accomplish it:

var string = '20:1:21,21:0:21';
var regex = /(\d+):(\d+):(\d+)/g;
var match;
var result = {};

while (match = regex.exec(string)) {
    result[match[2]] = {[match[1]]: match[3]};
}

console.log(result);

Upvotes: 1

trincot
trincot

Reputation: 350137

Your JS code seems to expect an array as input, but your input is a string. Also, you define result as a plain object, but really want an array...

Here is how you can do it in JavaScript.

var input = "20:1:21,21:0:21";

var result = input.split(",")
     .map(s => s.split(":"))
     .reduce((acc, [a,b,c]) => (acc[b] = {[a]: c}, acc), []);

console.log(result);

Upvotes: 3

Related Questions