Javascript member union?

For any object with elements that look like this:

target
{
    x1 : 1
    x2 : 2
    x3 : 3
    y1 : 6
    y2 : 5
    y3 : 4
}

I need to convert the object to something like this:

target
{
    x : [1, 2, 3]
    y : [6, 5, 4]
}

From the basic JavaScript that I know, it seems that the following function will work:

function joinParameters(target, paramName) {
    var count = 1;
    var array = [];
    var name = paramName.concat(count);
    var value = target[name];
    while (typeof value != undefined) {
        array.push(value);
        name = paramName.concat(count);
    }
    target[paramName] = array;
}

So, I can say joinParameters (target, "x"); The problem, however, is that

    var value = target[name];

always undefined. I monitored the code in FireBug to make sure that the target has a property that I am trying to get, and it is. So I'm not quite sure what happened.

If jQuery has an elegant way to do this, I would prefer this solution.

+3
source share
4 answers

Using underscore.js:

_(target).keys().reduce(function(memo, key){
    var split = /([^\d]+)([\d]+)/.exec(key);
    memo[split[1]] = memo[split[1]]||[];
    memo[split[1]][parseInt(split[2],10)-1] = target[key];
    return memo;
},{});

Working example:

http://jsfiddle.net/PLgN5/

+3
source
function joinParams(target) {
    var p;

    for (prop in target) {
        p = prop.substr(0, 1);

        if (!target[p]) {
                target[p] = [];
        }

        target[p].push(target[prop]);
    }

    return target;
}

target =
{
    x1 : 1,
    x2 : 2,
    x3 : 3,
    y1 : 6,
    y2 : 5,
    y3 : 4
}

target = joinParams(target);
+3
source

:

function joinParams(o) { 
    var ret = {},
        key;
    for(var i in o) {
        key = i.substr(0,1);
        ret[key] = ret[key] ? ret[key].push(o[i]) && ret[key] : [o[i]];
    } 
    return ret;
}


var target = /* original object */
target = joinParams(target);
+2

(.. ). Fix:

function joinParameters(target, paramName) {
    var count = 1;
    var array = [];
    var name = paramName.concat(count);
    var value = target[name];
    while (value != undefined) {   /* typeof value will return "undefined". */
        array.push(value);
        /* You need to increment 'count'. */
        name = paramName.concat(++count);
        value = target[name];
    }
    target[paramName] = array;
}

...

joinParameters(target, "x");

, x target, x1, x2, ..., x6 - target. , y, , , "".

zachallia .

+1
source

Source: https://habr.com/ru/post/1795646/


All Articles