javascript - Javascript在Excel中将两列名称合并为一列
问题描述
我正在使用 Data Miner 从网站表中抓取名称列表。我正在尝试将名称添加到 Excel 列中。被抓取的名称采用姓氏,名字格式。以下是一些供参考的名称。我想重新排列名称,使名字排在姓氏之前并删除逗号。我已经能够拆分名称,使用下面的代码在第 1 列中添加名字,在第 2 列中添加姓氏。我无法将名称带回第一列。如果有人能告诉我如何做到这一点,那就太好了。此外,Ted Potter Jr. 先生的名字中有 2 个逗号。我能做些什么来确保格式与其余名称匹配,但在 Potter 和 Jr. 之间留下逗号?
- 安秉宪
- 安瑟,亚伯拉罕
- 安德森,马克
- 盔甲,瑞恩
- 巴德利,亚伦
- 贝克,克里斯
- 巴恩斯,瑞奇
- 伯杰,丹尼尔
小波特,泰德
var cleanup = 函数(结果){
// 这个例子展示了你可以遍历每行 // 你抓取结果的数据并更改每列的值
//调试器;// 取消注释此行以启用在 Chrome Inspector 中调试您的脚本
$.each(results, function(){ // 遍历每行抓取的数据
var parts = this.values[0].split(', '); // get value from column 1 and split it by ' ' var first_name = parts[parts.length - 1]; //Loop through the remaining elements //for "Baker, Chris" this will just be one loop var second_name = ""; for (var i = 0; i < parts.length - 1; i++) { //if i = 0 then just add the element otherwise //if i > 0 then add what is already there plus space plus next element if (i > 0) { //this.values[1] = this.values[1] + " " + parts[i]; second_name = second_name + ", " + parts[i]; }else { //this.values[1] = parts[i]; second_name = parts[i]; } } this.values[0] = first_name + " " + second_name;
控制台.log(this.values[0]);
});返回结果;// 返回修改后的结果 };
解决方案
如果没有上下文/更多代码,这有点难以判断,但总的来说,我认为这样的事情会起作用。
如果您想要一个真实的示例,请参见此处:https ://jsfiddle.net/pqjd2h5a/
- 做你的分裂
- 将数组的最后一个元素放在前面/到第 1 列
- 循环遍历剩余元素并将它们在第 2 列连接在一起
- 在第 3 列中将名字和姓氏连接在一起
也许是这样的:
var cleanup = function(results) {
$.each(results, function(){
//split the string of "Baker, Chris" into an array of ["Baker", "Chris"]
//split the string of "Potter, Jr., Ted" into an array of ["Potter", "Jr.", "Ted"]
var parts = this.values[0].split(', ');
//set the first column to the last element of the array. i.e. "Chris" or "Ted"
//this.values[0] = parts[parts.length - 1];
var first_name = parts[parts.length - 1];
//Loop through the remaining elements
//for "Baker, Chris" this will just be one loop
var second_name = "";
for (var i = 0; i < parts.length - 1; i++) {
//if i = 0 then just add the element otherwise
//if i > 0 then add what is already there plus space plus next element
if (i > 0) {
//this.values[1] = this.values[1] + " " + parts[i];
second_name = second_name + " " + parts[i];
}else {
//this.values[1] = parts[i];
second_name = parts[i];
}
}
//concatenate the results together in the third column
//i.e. "Chris Baker" or "Ted Potter Jr."
//this.values[2] = this.values[0] + " " + this.values[1];
//Or now output only in first column
this.values[0] = first_name + " " + second_name;
});
return results;};
推荐阅读
- java - OpenAPI 不验证字符串数组查询参数值
- python - 添加一个方法,如果当前日期是星期一,我们添加 4 个日期,则要返回的日期是星期五
- python - 从四元数获得相对角速度
- database - Neo4j 基于条件的输出
- python - Selenium 和 Python:使用动态 XPATH 查找元素
- javascript - 从 Websocket 函数中获取值
- debian - 使用 LUKS 接收“此密码没有可用的密钥”
- windows - 批处理:从文件名(子字符串)创建文件夹
- javascript - 在 selectionchange() 上从数组中弹出元素
- r - 两个两个(或按名称)绑定列表中的数据框 - R