需要检查密钥是否已经存在并且特朗普值,javascript

时间:2015-10-30 17:38:20

标签: javascript arrays object

var data = [
    ["default_PROJECT", "Allow", "Connect", "Allow", "AddComment", "Allow", "Write",
        "Allow", "ViewComments", "Allow", "ExportData", "Allow", "ExportImage", "Allow",
        "ViewUnderlyingData", "Allow", "Read", "Allow", "ShareView", "Allow", "Filter"
    ],
    ["testing_PROJECT", "Allow", "ExportImage", "Allow", "Write", "Allow", "ViewComments",
        "Allow", "ShareView", "Allow", "Filter", "Allow", "ExportData", "Allow", "Connect", "Allow",
        "Read", "Allow", "ViewUnderlyingData", "Allow", "AddComment", "Allow", "ViewComments", "Deny", "ExportData", "Allow",
        "AddComment", "Deny", "Write", "Allow", "Read", "Deny", "ExportXml", "Deny", "ShareView", "Allow", "Connect", "Allow", "ChangeHierarchy", "Allow",
        "WebAuthoring", "Deny", "ViewUnderlyingData", "Deny", "Filter", "Deny", "ExportImage"
    ]
];


var result = [];
for (var i = 0, len = data.length; i < len; i++) {
    var list = data[i];
    result[i] = {
        Project: list[0]
    };
    for (var j = list.length - 1; j >= 1; j = j - 2) {
        var key = list[j];
        var value = list[j - 1];
        result[i][key] = value;
    }
}
console.log(result);

对于某些键,可能有多个值。如果现有值为allow且对同一个键有值deny,则需要键的新值为deny。例如,在第二个数组中,键&#34; ExportImage&#34;应该具有&#34; Deny&#34;而不是&#34;允许&#34;。我创建了对象但是如何检查是否应该覆盖这些值?

1 个答案:

答案 0 :(得分:1)

物品之美在于你可以检查它们的价值;)因为&#34;否定&#34;优于所有其他变量 - 然后让它赢,或者是最后一个值。

案例1:允许,拒绝,允许,Foo,Bar =&gt;的拒绝
案例2:允许,Foo,Bar,允许,Baz =&gt;的巴兹

for (var j = list.length - 1; j >= 1; j = j - 2) {
    var key = list[j];
    var value = list[j - 1];
    if( result[i][key] !== "Deny" ) {
        result[i][key] = value;
    }
}