0

I want to return a json data in my function, like this:

const getJSON = () => {
    const array = [];
    const obj = {};
    const str1 = 'abc';
    const str2 = '123';
    array.push(str1, str2);

    return obj;
};

I want the output like:

obj =
    {
       str1: 'abc',
       str2: '123',
    }

I want response a JSON that front-end can use easily, is it posible?

huihui
  • 11
  • 1
  • 4
  • array to JSON ... `JSON.stringify` - but the result you want is not JSON, it's an object .... that can be created lke `obj = {str1, str2}` – Jaromanda X Aug 10 '22 at 06:42
  • There's no [JSON](https://www.json.org/json-en.html) in your script (hence the name of the function is wrong) -> [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – Andreas Aug 10 '22 at 06:50
  • Arrays don't store information about the original variable names used, so it is impossible to determine that data when you wish to covert it to an object. – Miguel Guthridge Aug 10 '22 at 07:02

1 Answers1

0

Since you want {"str1":"abc","str2":"123"}" => You want an Object (not an array)

Fix

const getJSON = () => {
    const obj:any = {};
    obj.str1 = 'abc';
    obj.str2 = '123';
    return obj;
};

console.log(JSON.stringify(getJSON())); // {"str1":"abc","str2":"123"}" 
basarat
  • 261,912
  • 58
  • 460
  • 511