Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

javascript - complex array merge using nested loop

my challenge is to merge 2 arrays base on uId.

var job = [{
    "uId": 1
}, {
    "uId": 2
}]

var jobDetails = [{
    "uId": 1,
    "salary": 5000
}, {
    "uId": 2,
    "salary": 5000
}]

so far I stuck at

foreach(var job as var k=>var &arr)
{
    if(arr->{'uId'}==2)
    {
        arr->{'salary'}=salary;
    }
}

which hardcode 2 to find job array's uId.

how can I produce something like

var job = [{
    "uId": 1,
    "salary": [{
        "uId": 1,
        "salary": 5000
    }]
}, {
    "uId": 2,
    "salary": [{
        "uId": 2,
        "salary": 5000
    }]

}];
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As discussed in chat, here is a javascript example that builds what you asked for:

var tabs = [{"uId":"2","tabId":1,"tabName":"Main","points":"10","active":"true"},{"uId":"3","tabId":2,"tabName":"Photography","points":"20","active":""}];

var tasks = [{"taskId":3,"taskName":"Sing Sing Gem","priorty":3,"date":"2014-04-25","done":0,"tabId":1,"uId":"2"},{"taskId":4,"taskName":"Shooting","priorty":4,"date":"2014-04-25","done":0,"tabId":2,"uId":"3"}];

var uidSet = {};

var UIDSortFunction = function(a,b){
    uidSet[a.uId] = 1;
    uidSet[b.uId] = 1;
    return a.uId - b.uId;
};
tabs.sort(UIDSortFunction);
tasks.sort(UIDSortFunction);

var endResult = [];

var i, j, tabsLen = tabs.length, tasksLen = tasks.length, k = 0;


for(var key in uidSet)
{
    if(uidSet.hasOwnProperty(key))
    {
        endResult.push({
            uId : key,
            tabs:[],
            tasks:[]
        });
        for(i = 0; i < tabsLen; ++i)
        {
            if(tabs[i].uId === key)
                endResult[k].tabs.push({
                    tabId:tabs[i].tabId,
                    tabName: tabs[i].tabName,
                    points: tabs[i].points
                });
        }
        for(j = 0; j < tasksLen; ++j)
        {
            if(tasks[j].uId === key)
                endResult[k].tasks.push({
                    uId: tasks[j].uId,
                    tabId:tasks[j].tabId,
                    taskName: tasks[j].taskName
                });
        }
        ++k;
    }
}

console.log(endResult);

http://jsfiddle.net/fnf33/2/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...