要将Key:Value对仅附加到我的数组元素一次!

时间:2011-05-09 10:52:53

标签: javascript

var people =[{title:'Alan', hasChild:true},
            {title:'Alice', hasDetail:true},
            {title:'Amos',},
            {title:'Alonzo'},
            {title:'Brad'},
            {title:'Brent'},    
            {title:'Billy'},    
            {title:'Brenda'},   
            {title:'Callie'},
            {title:'Cassie'},   
            {title:'Chris'}];

默认情况下,我的数组不包含任何键,值对header:'A'header:'B',`header'C'等......我在运行时添加它们。

for (i = 0, len = people.length; i < len; i++) {
            var headerValue = people[i].header = people[i].title.charAt(0);
}

通过这样做,我的数组有一个新的键值对'Header:'FirstLetter of the title'

var people =[{title:'Alan', hasChild:true, header:'A'},
                {title:'Alice', hasDetail:true,header:'A'},
                {title:'Amos',header:'A'},
                {title:'Alonzo',header:'A'},
                {title:'Brad',header:'B'},
                {title:'Brent',header:'B'}, 
                {title:'Billy',header:'B'}, 
                {title:'Brenda',header:'B'},    
                {title:'Callie',header:'C'},
                {title:'Cassie',header:'C'},    
                {title:'Chris',header:'C'}];

我不想将header:value添加到所有元素中,如果我将header:value添加到标题以'A'开头的元素中,那么其标题以A开头的元素应该是被忽略了。 我想要这种格式的数组。

var people =[{title:'Alan', hasChild:true, header:'A'},
                    {title:'Alice', hasDetail:true,},
                    {title:'Amos'},
                    {title:'Alonzo'},
                    {title:'Brad',header:'B'},
                    {title:'Brent'},    
                    {title:'Billy'},    
                    {title:'Brenda'},   
                    {title:'Callie',header:'C'},
                    {title:'Cassie'},   
                    {title:'Chris'}];

我的更新代码....

    function SortByName(x,y) {        
      return ((x.LastName == y.LastName) ? 0 : ((x.LastName > y.LastName) ? 1 : -1 ));    
    }

    function RenderPatientSearchData(PatientSearchResponse){
        var PatientSearchData = JSON.parse(PatientSearchResponse);
        var results = PatientSearchData['PatientSearchResult'];
        results.Patient.sort(SortByName);
        rowData = [];

        var prevHeader = '';
        for (i = 0, len = results.Patient.length; i < len; i++) {
            var headerValue = results.Patient[i].header = results.Patient[i].LastName.charAt(0);    
                if (headerValue !== prevHeader) {      
                    headerValue = results.Patient[i].header = results.Patient[i].LastName.charAt(0);    
             }
            prevHeader = headerValue;

....... some code... 

}

1 个答案:

答案 0 :(得分:1)

跟踪循环中的标头值:

var prevHeader = '';
for (i = 0, len = people.length; i < len; i++) {
    var headerValue = people[i].title.charAt(0);
    if (headerValue !== prevHeader) {
      people[i].header = headerValue;
    }
    prevHeader = headerValue;
}

注意:要使其正常工作,必须事先对people数组进行排序