根据优先级获取数组的值

时间:2015-03-17 07:05:55

标签: javascript arrays sorting object

我有一个基于优先级的对象数组,我需要形成一个对象数组。以下是我尝试的代码

var data_res = [{
   "ACTION_TYPE": "CREATE",
   "EXECUTION_TYPE": "N_EXECUTION"
   }, 
   { "ACTION_TYPE": "CREATE",
  "EXECUTION_TYPE": "R_PRE_EXECUTION"
   }
];
var arr =  ["R_PRE_EXECUTION", "S_PRE_EXECUTION", "N_EXECUTION"];
for (var i = 0; i < data_res.length; i++) {
for (var temp in arr) {
    if (data_res[i].RULE_EXECUTION_TYPE.indexOf(arr[temp])>-1) {
        console.log("data")
        console.log(JSON.stringify(data_res[temp]))
    }
}

我得到的输出是

data
undefined
data
{"ACTION_TYPE":"CREATE","EXECUTION_TYPE":"N_EXECUTION"}

我希望数据基于我的数组arr。就像首先R_PRE_EXECUTION数据必须形成S_PRE_EXECUTION然后N_PRE_EXECUTION一样,不知道我哪里出错了。

3 个答案:

答案 0 :(得分:5)

您似乎希望根据data_res给出的顺序对arr进行排序。

var data_res = [{
    "ACTION_TYPE": "CREATE",
    "EXECUTION_TYPE": "N_EXECUTION"
}, {

    "ACTION_TYPE": "CREATE",
    "EXECUTION_TYPE": "R_PRE_EXECUTION"
}]

var arr = ["R_PRE_EXECUTION", "S_PRE_EXECUTION", "N_EXECUTION"];

data_res.sort(function(a, b) {
  var aKey = arr.indexOf(a.EXECUTION_TYPE);
  var bKey = arr.indexOf(b.EXECUTION_TYPE);  
  return aKey - bKey;
});

document.write("<pre>" + JSON.stringify(data_res,0,3));

答案 1 :(得分:2)

@ georg的解决方案效果很好。这是另一种方式。

&#13;
&#13;
var data_res = [{
    "ACTION_TYPE": "CREATE",
    "EXECUTION_TYPE": "N_EXECUTION"
  },
  {
    "ACTION_TYPE": "CREATE",
    "EXECUTION_TYPE": "R_PRE_EXECUTION"
}]

var arr = ["R_PRE_EXECUTION", "S_PRE_EXECUTION", "N_EXECUTION"];

var ordered = [];

for (var j = 0; j < arr.length; j++) {
    for (var i = 0; i < data_res.length; i++) {
        if (arr[j].indexOf(data_res[i].EXECUTION_TYPE) > -1) {
            ordered.push(data_res[i]);
        }
    }
}

document.write('<pre>' + JSON.stringify(ordered, 0,3) + '</pre>');
&#13;
&#13;
&#13;

答案 2 :(得分:0)

第一个indexOf与数组的第三个元素匹配,给出2的索引。 data_res只有2个元素,因此data_res[temp]给出undefined值。

你可以这样做

var data_res = [{
    "ACTION_TYPE": "CREATE",
    "EXECUTION_TYPE": "N_EXECUTION"
}, {

    "ACTION_TYPE": "CREATE",
    "EXECUTION_TYPE": "R_PRE_EXECUTION"
}]

var arr = ["R_PRE_EXECUTION", "S_PRE_EXECUTION", "N_EXECUTION"];

for (var i = 0; i < data_res.length; i++) {
        if ((arr.indexOf(data_res[i].EXECUTION_TYPE)) > -1) {
            console.log("data")
            console.log(JSON.stringify(data_res[i]))
        }
}