javascript - 您可以使用字符串模板文字将整个对象作为字符串返回吗?

标签 javascript string object

我有这个问题:

This function should take an argument as an object, and return a string with the user's details in the form:

'name: Mitch, age: 27, language: Javascript'

Note - this is a good use case of string template literals.

function createUserString(userObj) {

}

任何人都可以帮助解释如何将对象属性转换为完整字符串吗?

最佳答案

我想使用Object.entries()Array.prototype.reduce()一起可以解决您的问题。阅读他们的文档:

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for...in loop.

看看可能的好解决方案:

const user = {
  name: 'Mitch',
  age: 27,
  language: 'JavaScript',
  nickName: 'Cool Mitch' // just added one more property for representation
};

const createUserString = user => {
  const entries = Object.entries(user);
  return entries.reduce((a, [k,v]) => a ? `${a}, ${k}: ${v}` : `${k}: ${v}`, '');
}

console.log(createUserString(user));

希望对您有所帮助!

关于javascript - 您可以使用字符串模板文字将整个对象作为字符串返回吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59922764/

相关文章:

javascript - 使用 JavaScript 命名空间有什么危险吗?

c++ - 我将如何准确地获取打开的文件和文件中的名称并将它们放入我的字符串 vector 中?

c - 编写 Vending 程序,while 语句不会中断?

javascript - Sublime text 3 win 7 TernJS 和 tern_for_sublime 安装问题

javascript - 从 jQuery Each 元素中获取 ID 字段

php - 将转换为 json 字符串的对象发送到 php 脚本

object - QTP 中的 .Exist 超时如何工作?

Javascript 定义对象属性和函数的新方法?

javascript - 将事件函数绑定(bind)到类,但使用 removeEventListener 并删除其引用,从而使垃圾收集器能够正常工作

java - 查找字符串中某个重复字符/子字符串的每个位置