【问题标题】:Create One string from elements in an Array of Objects从对象数组中的元素创建一个字符串
【发布时间】:2021-04-07 20:43:13
【问题描述】:

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

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

我希望字符串是这样的

"John, Mike, Link or Mary"

我尝试使用family.toString(),但这给了我"John, Mike, Link, Mary",并且不允许我用“OR”替换“,”

【问题讨论】:

  • 这不是一个有效的结构,也不是一个数组。您发布了一个对象,其中包含不存在的重复键

标签: javascript node.js arrays react-native


【解决方案1】:

使用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);

【讨论】:

  • 可能想检查数组长度是否大于一,这样你就不会只得到"and John"
【解决方案2】:

我不认为有一个超级优雅的选择。最好的选择是:

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 ')

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

【讨论】:

    【解决方案3】:

    怎么样

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

    希望,这个问题是为学校作业准备的 :)

    【讨论】:

      猜你喜欢
      • 2018-03-09
      • 1970-01-01
      • 2015-01-23
      • 2019-07-30
      • 1970-01-01
      • 1970-01-01
      • 2015-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多