skip to Main Content

I want to generate this string from Array of Object.

String:

"{{ ""t"": 3, ""s"":910},{ ""t"": 6, ""s"":4030},{ ""t"": 10, ""s"":2300}}"

Array of Object

0: {t: 3,s: 910}
1: {t: 6,s: 4030}
2: {t: 10,s: 2300}

Can anyone guide me how to do it.

2

Answers


  1. You can do it using JSON.stringfy() function.
    Here is code.

    const arr = [
      { t: 3, s: 910 },
      { t: 6, s: 4030 },
      { t: 10, s: 2300 },
    ];
    const formattedString =
      '{' + arr.map((item) => JSON.stringify(item)).join(', ') + '}';
    console.log(formattedString);
    

    Hope this is helpful.

    Login or Signup to reply.
  2. Try the following code.

    const arr = [
      { t: 3, s: 910 },
      { t: 6, s: 4030 },
      { t: 10, s: 2300 },
    ];
    
    const result = arr.map(obj => {
      return Object.entries(obj).map(([key, value]) => `""${key}"": ${value}`).join(', ');
    }).map(str => `{ ${str} }`).join(', ');
    
    const finalResult = `"{{ ${result} }}"`;
    
    console.log(finalResult);
    

    log: "{{ { ""t"": 3, ""s"": 910 }, { ""t"": 6, ""s"": 4030 }, { ""t"": 10, ""s"": 2300 } }}"

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search