如何在Knockout中的arrayMap顶部放置一个特定的记录?

时间:2015-12-18 09:05:25

标签: javascript knockout.js

我在arrayMap中有一个非常简单的computed observable

self.Employees = ko.computed(function() {
    return ko.utils.arrayMap(self.EmployeeData(),

      function(data) {

        return {

          Name: data.EmployeeName,
          value: data.EmployeeID
        }

      });

  })

数据是JSON:

[{"Name" : "John"}, {"EmployeeID" : "1w23"}]

根据某些条件,是否有办法让特定员工位于列表顶部?简而言之,当我将数据绑定到en元素时,记录是顶部的第一个?

1 个答案:

答案 0 :(得分:1)

您只需重新排序self.EmployeeData()数组,并将其放在列表顶部,具体取决于条件。

这是一项简单的JavaScript任务。举个例子,请看:

Move an array element from one array position to another

或者,如果您不介意使用lodash,可以使用以下功能:

var moveToStart = function(list, predicate) {
  var found = _.remove(list, predicate);
  list.unshift.apply(list, found);
};

如本片段所示:



var list = [1,2,3,4,5];

var moveToStart = function(list, predicate) {
    var found = _.remove(list, predicate);
    list.unshift.apply(list, found);
};

$('#original').text(JSON.stringify(list));

moveToStart(list, function(e) { return e == 3;})
$('#moved3').text(JSON.stringify(list));

moveToStart(list, function(e) { return e%2 == 0;})
$('#movedEven').text(JSON.stringify(list));

moveToStart(list, function(e) { return e == 500;})
$('#moved500').text(JSON.stringify(list));


var list2 = [
 {name:'John', age: 41, },
 {name:'Frank', age: 23 },
 {name:'Anna', age: 37},
 {name:'Norah', age: 3}
];

$('#originalPeople').text(JSON.stringify(list2,null,2));

moveToStart(list2, function(p) { return p.age < 30});
$('#movedPeople').text(JSON.stringify(list2,null,2));
&#13;
p {
  font-family: Segoe, Arial;
  font-weight: bold;
  margin: 15px 0 0 0;
}

pre {
  margin: 0;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>Original:</p>
<pre id="original"></pre>
<p>After 3 to start:
  moveToStart(list, function(e) { return e == 3;})
<pre id="moved3"></pre>
<p>After even numbers to start: 
  moveToStart(list, function(e) { return e%2 == 0;})</p>
<pre id="movedEven"></pre>
<p>After non-existen number to start: 
  moveToStart(list, function(e) { return e == 500;})</p>
<pre id="moved500"></pre>
<br/>
<br/>
<p>Original list of persons<p>
<pre id="originalPeople"></pre>
<p>After moving younger than 30 to start<br/>
moveToStart(list2, function(p) { return p.age &lt; 30});
</p>
<pre id="movedPeople"></pre>
&#13;
&#13;
&#13;