对象数组中的属性不匹配

时间:2017-04-13 04:33:02

标签: javascript

我有一个名单(第一个+最后一个)。我想使所有的全名和姓氏不匹配,以至于新列表和初始名称列表之间没有全名。

Mike,Pence
Tom,ho
Dave, hike
.......so on  ...

有效输出将是:

Mike,hike
Tom,pence
Dave,ho
.......so on  ...

我的数据是

      var name = [ {
       firstN: 'Mike',
       lastN: 'Pence',
       fullName: 'Mike Pence'
    },
    { 
       firstN: 'Tom',
       lastN: 'Ho',
       fullName: 'Tom Ho'
    },
    { 
       firstN: 'Dave',
       lastN: 'hike',
       fullName: 'Dave Hike
    }

................等等达到100多岁  ]

预期输出:

 New List  = [ {
       firstN: 'Mike',
       lastN: 'Hike',
       fullName: 'Mike Hike'
    },
    { 
       firstN: 'Tom',
       lastN: 'Pence',
       fullName: 'Tom Pence'
    },
    { 
       firstN: 'Dave',
       lastN: 'ho',
       fullName: 'Dave Ho
    }

2 个答案:

答案 0 :(得分:0)

你在评论中澄清说你的初始名单中没有任何重复的名字或姓氏,所以你需要做的就是“滑动”每个人的姓氏,以便与前一个人的名字配对:

var input = [{"firstN":"Andrew","lastN":"Anderson","fullName":"Andrew Anderson"},{"firstN":"Belinda","lastN":"Brown","fullName":"Belinda Brown"},{"firstN":"Clare","lastN":"Charleston","fullName":"Clare Charleston"},{"firstN":"David","lastN":"Downer","fullName":"David Downer"},{"firstN":"Edwin","lastN":"Edwards","fullName":"Edwin Edwards"},{"firstN":"Francine","lastN":"Fellows","fullName":"Francine Fellows"},{"firstN":"Gary","lastN":"Green","fullName":"Gary Green"},{"firstN":"Harriot","lastN":"Harcourt","fullName":"Harriot Harcourt"},{"firstN":"Irwin","lastN":"Inglesson","fullName":"Irwin Inglesson"},{"firstN":"Jennifer","lastN":"Jones","fullName":"Jennifer Jones"}]

var output = input.map(function(p, i, a) {
  var next = (i + 1) % a.length
  return {
    firstN: p.firstN,
    lastN: a[next].lastN,
    fullName: p.firstN + ' ' + a[next].lastN
  }
})

console.log(output)

答案 1 :(得分:0)

你可以这样做。只需要改变shuffling数组中的逻辑,因为有时候它会在同一个索引处生成相同的值。

var nameList =[{firstN:'Tom',lastN:'Ho',fullName:'Tom Ho'},{firstN:'Mike',lastN:'Pence',fullName:'Mike Pence'},{firstN:'Dave',lastN:'Hike',fullName:'Dave Hike'}]

var newNameList = [];

var length = nameList.length;
for (var a=[],i=0;i<length;++i) a[i]=i;

function shuffle(array) {
  var tmp, current, top = array.length;
  if(top) while(--top) {
    current = Math.floor(Math.random() * (top + 1));
    tmp = array[current];
    array[current] = array[top];
    array[top] = tmp;
  }
  return array;
}
a = shuffle(a);

for(var i=0;i<length;i++){
  newNameList[i] = {};
  newNameList[i].firstN = nameList[i].firstN;
  newNameList[i].lastN = nameList[a[i]].lastN;
  newNameList[i].fullName = newNameList[i].firstN + " "+       newNameList[i].lastN;
}

console.log(newNameList)