将数据从一个阵列复制到另一个阵列

时间:2014-07-11 10:00:54

标签: javascript node.js

我有两个数组,如下所示。

var obj1 = [
        {
            "POST": "Developer",
            "USERNAME": [
                "User1",
                "User2"
            ]
        },
        {
            "POST": "Tester",
            "USERNAME": [
                "User3"
            ]
        }
    ]

var obj2 = [
        {
            "USERNAME": "User1",
            "USER_PASSWORD": "test1"
        },
        {
            "USERNAME": "User2",
            "USER_PASSWORD": "test2"
        },
        {
            "USERNAME": "User3",
            "USER_PASSWORD": "test3"
        }
    ]

obj1开始,我希望将POST值附加到obj2中的相应用户。

最终结果应如下所示。

[
    {
        "USERNAME": "User1",
        "USER_PASSWORD": "test1",
        "POST": "Developer"
    },
    {
        "USERNAME": "User2",
        "USER_PASSWORD": "test2",
        "POST": "Developer"
    },
    {
        "USERNAME": "User3",
        "USER_PASSWORD": "test3",
        "POST": "Tester"
    }
]

2 个答案:

答案 0 :(得分:1)

试试这个:

var obj1 = [
                {"POST":"Developer","USERNAME":["User1","User2"]},
                {"POST":"Tester","USERNAME":["User3"]}
            ];
            var obj2 = [
                {"USERNAME":"User1","USER_PASSWORD":"test1"},
                {"USERNAME":"User2","USER_PASSWORD":"test2"},
                {"USERNAME":"User3","USER_PASSWORD":"test3"}];
            var obj3=[];

            obj1.forEach(function(eachObj1) {
                obj2.forEach(function(eachObj2) {
                    if(eachObj1.USERNAME.indexOf(eachObj2.USERNAME) >= 0) {
                        console.log("in if")
                        eachObj2.POST = eachObj1.POST;
                        obj3.push(eachObj2);
                    }
                });
            });

答案 1 :(得分:-2)

试试这个,

var obj1 = [{"POST":"Developer","USERNAME":["User1","User2"]},{"POST":"Tester","USERNAME":["User3"]}];
var obj2 = [{"USERNAME":"User1","USER_PASSWORD":"test1"},{"USERNAME":"User2","USER_PASSWORD":"test2"},{"USERNAME":"User3","USER_PASSWORD":"test3"}];
$.each(obj2,function(i,val){
   $.each(obj1,function(index,innerVal){

        var post=innerVal.POST;
        $.each(innerVal.USERNAME,function(i,user){
            if(user==val.USERNAME){
                val.POST=post;
            }
        });
    });
});
alert(JSON.stringify(obj2));

Demo