如何基于另一个键值将新的键值对添加到数组中的对象

时间:2019-01-23 13:44:14

标签: javascript arrays

我有2个JSON对象:

obj1 = [{
    "screenCode": "usr_ooo_master",
    "screenName": "Out Of Office Master"
    }, {
    "screenCode": "usr_user_master",
    "screenName": "User Master"
    }]

obj2 = [{
    "id": "10a310a8-6f01-4082-af86-bb73019cff8d",
    "cascadeImpact": {
        "screenCode": "usr_user_master",
        "impactedModuleCode": "borrower2"
    },
    "screenImpactedCode": "bor_address1"
}, {
    "id": "308c8058-5e98-4b99-a1c6-82e9e5c93787",
    "cascadeImpact": {
        "screenCode": "usr_ooo_master",
        "impactedModuleCode": "borrower2"
    },
    "screenImpactedCode": "bor_address2"
}]

我想根据“ screenCode”向obj2添加一个新的键值对。因此,例如。我要向obj2第一个元素添加“ screenName”:“ User Master”。我该怎么做。

3 个答案:

答案 0 :(得分:1)

您可以将相应的键/值对移至Map并使用map的结果更新对象。

var array1 = [{ screenCode: "usr_ooo_master", screenName: "Out Of Office Master" }, { screenCode: "usr_user_master", screenName: "User Master" }],
    array2 = [{ id: "10a310a8-6f01-4082-af86-bb73019cff8d", cascadeImpact: { screenCode: "usr_user_master", impactedModuleCode: "borrower2" }, screenImpactedCode: "bor_address1" }, { id: "308c8058-5e98-4b99-a1c6-82e9e5c93787", cascadeImpact: { screenCode: "usr_ooo_master", impactedModuleCode: "borrower2" }, screenImpactedCode: "bor_address2" }],
    map = new Map(array1.map(({ screenCode, screenName }) => [screenCode, screenName]));

array2.forEach(({ cascadeImpact }) =>
    cascadeImpact.screenName = map.get(cascadeImpact.screenCode));

console.log(array2);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

obj2['screenName'] = 'User Master'

我唯一但只有一点怀疑的是在obj2中,您具有单元素数组。如果上述方法不起作用,则可以始终在obj2上进行迭代,例如(JQuery版本):

$.each(obj2, function(index, element) {
   element['screenName'] = 'User Master';
}

请记住,您在数组中只有一个元素-它只会迭代一次(但是资源饥饿感会比您仅像第一个代码中那样进行分配要大)

答案 2 :(得分:0)

如果您想将密钥添加到特定项目,只需使用该项目的密钥:obj2 [0] ['screenName'] =“ test”否则下面将出现循环:

obj2 = [{
    "id": "10a310a8-6f01-4082-af86-bb73019cff8d",
    "cascadeImpact": {
        "screenCode": "usr_user_master",
        "impactedModuleCode": "borrower2"
    },
    "screenImpactedCode": "bor_address1"
}, {
    "id": "308c8058-5e98-4b99-a1c6-82e9e5c93787",
    "cascadeImpact": {
        "screenCode": "usr_ooo_master",
        "impactedModuleCode": "borrower2"
    },
    "screenImpactedCode": "bor_address2"
}]

for(var i=0;i < obj2.length; i++){
   obj2[i]['screenName'] = 'Master-' + (i+1);
   obj2[i]['screenCode'] = 'Code-' + (i+1);
}

console.log(obj2)