如何在javascript中将对象转换为字符串?

时间:2019-05-31 16:44:09

标签: javascript

我有一个函数,该函数应将一个对象作为参数并以'name: David, age: 22, language: PHP'的形式返回一个字符串

我写的代码。

function UserString(obj) {
  return obj.toString();
}

我要运行的代码:

      describe('UserString', () => {
        it('returns a string containing "name : <user\'s name>"', () => {
          const david= { name: 'David', age: 22, language: 'PHP' };
          const actual = createUserString(david);
          expect(actual.includes('name: David')).to.be.true;
        });
        it('returns a string containing "age : <user\'s age>"', () => {
          const david= { name: 'David', age: 22, language: 'PHP' };
          const actual = UserString(david);
          expect(actual.includes('age: 22')).to.be.true;
        });
        it('returns a string containing "language : <user\'s language>"', () => {
          const david= { name: 'David', age: 22, language: 'PHP' };
          const actual = UserString(david);
          expect(actual.includes('language: PHP')).to.be.true;
        });
        it("returns a whole string with all of the user's details", () => {
          const david= { name: 'David', age: 22, language: 'PHP' };
          let actual = UserString(david);
          expect(actual.includes('name: David, age: 22, language: Javascript')).to
            .be.true;

          const ant = { name: 'Ant', age: 28, language: 'Java' };
          actual = UserString(ant);
          expect(actual.includes('name: Ant, age: 28, language: Java')).to.be.true;
        });
      });

4 个答案:

答案 0 :(得分:1)

let toString = ({name, age, language}) => `name: ${name}, age: ${age}, language: ${language}`;

const david = { name: 'David', age: 22, language: 'PHP' };

console.log(toString(david));

如果您想更通用一些:

let toString = obj => Object.entries(obj).map(([k, v]) => `${k}: ${v}`).join(', ');

const david = { name: 'David', age: 22, language: 'PHP', favoriteFood: 'blue' };

console.log(toString(david));

答案 1 :(得分:1)

如果您的对象就像

const obj = { name: "John", age: 30, city: "New York" };

使用JavaScript函数JSON.stringify()将其转换为字符串。 像这样JSON.stringify(obj)。 那么您将得到以下字符串:

"{"name":"John","age":30,"city":"New York"}"

答案 2 :(得分:1)

如果您想在不应用 JSON.stringify() 函数的情况下将对象转换为字符串,请应用此技术

let obj = { 
  x: 1, 
  y: 'HelloWorld',
  toString: function(){
    return `${this.x}, ${this.y}`;
  }
};

let result = String(obj);

console.log(result, 'type --> ', typeof result);

答案 3 :(得分:0)

var data = {name: "john", age: 30}
var str = String(`${JSON.stringify(data)}`)  // "{\"name\":\"john\",\"age\":30}"
var btoas = btoa(str)  // "eyJuYW1lIjoiam9obiIsImFnZSI6MzB9"
var atobs = atob(btoas)  // "{\"name\":\"john\",\"age\":30}"
var myRealData = JSON.parse(atobs)  //{name: "john", age: 30}

` BOYAA !! `