如何使用新数组中的数据填充现有数组?

时间:2016-12-21 07:32:31

标签: javascript arrays

现有数组中的对象:

[
    {
        "contact": {
            "email": {
                "home": "",
            },
            "phone": {
                "cell": "+91-1234-567-891",
                "work": ""
            }
        },
        "createdDate": "2016-12-21T07:17:44.096Z",
        "name": "Test"
    },
    {
        "contact": {
            "email": {
                "home": "",
            },
            "phone": {
                "cell": "+91-1234-567-892",
                "work": ""
            }
        },
        "createdDate": "2016-12-21T07:17:44.096Z",
        "name": "Test2"
    }
]

新阵列数据:

[
    {
        "contact": {
            "email": {
                "home": "sample@gmail.com",
            },
            "phone": {
                "cell": "+91-1234-567-891",
                "work": ""
            }
        },
        "createdDate": "2016-12-21T07:17:44.096Z",
        "name": "Test1"
    },
    {
        "contact": {
            "email": {
                "home": "",
            },
            "phone": {
                "cell": "+91-1234-567-892",
                "work": ""
            }
        },
        "createdDate": "2016-12-21T07:17:44.096Z",
        "name": "Test2"
    },
    {
        "contact": {
            "email": {
                "home": "",
            },
            "phone": {
                "cell": "+91-1234-567-893",
                "work": ""
            }
        },
        "createdDate": "2016-12-21T07:17:44.096Z",
        "name": "Test3"
    }
]

如果你看到,在新数组中添加了额外的对象,我必须使用新数据填充现有数组。

有时,用户可能会更改他们的电子邮件地址,我必须在新阵列中更新现有阵列中的相同内容。我该怎么做?

通过我的尝试,它复制了现有数组中的对象。

for(var i = 0; i < newArr.length; i++) {
        for(var k = 0; k < oldArray.length; k++){
            if(newArr[i].contact.phone.cell && newArr[i].contact.phone.cell === oldArray[k].contact.phone.cell){
                console.log('MATCHED...........', newArr[i]);
                newArr.splice(i, 1);
            }
        }
    }

0 个答案:

没有答案