从对象数组中的元素创建一个字符串



我正试图从对象family的数组中创建一个字符串,并将它们用逗号分隔,除了最后一个元素Mary

const family = [
{Person: {
name: John
}}, {Person: {
name: Mike
}}, {Person: {
name: Link
}}
, {Person: {
name: Mary
}}];

我希望字符串像这个

"John, Mike, Link or Mary"

我尝试使用CCD_ 3,但这给了我CCD_"用一个";OR";

使用pop()获取(并删除(姓氏。然后使用join()添加其余部分。

感谢@charlietfl建议检查名称的数量,以防止出现类似and John的情况。

const family = [
{ Person: { name: "John" } },
{ Person: { name: "Mike" } },
{ Person: { name: "Link" } },
{ Person: { name: "Mary" } }
];
// Get all the names
const names = family.map((x) => x.Person.name);
// Get result based on number of names
let result = '';
if (names.length === 1) {
// Just show the single name
result = names[0];
} else {

// Get last name
const lastName = names.pop();

// Create result 
result = names.join(', ') + ' and ' + lastName;
}

// Show output
console.log(result);

我不认为有超级elogant选项。最好的选择是:

function joinWord(arr, sep, finalsep) {
return arr.slice(0,-1).join(sep) + finalsep + arr[arr.length-1];
}

然后

joinWord(family.map(x=>x.person.name), ', ', ' or ');

您可以使用以牺牲性能和模块性为代价,使调用变得更好一些

Array.prototype.joinWord = function joinWord(sep, finalsep) {
return this.slice(0,-1).join(sep) + finalsep + this[this.length-1];
}
family.map(x=>x.person.name).joinWord(', ', ' or ')

但这只是一个好主意,如果这会在你的项目中出现很多,而且你的项目永远不会成为更大项目的一部分。它影响每个数组。

怎么样

let sp = ' or ';
family.map(x => x.Person.name)
.reduceRight(
(x,y) => {
const r = sp + y + x;
sp = ', ';
return r;
}, '')
.replace(', ', '');

希望,这个问题是为学校的家庭作业:(

相关内容

最新更新