Search code examples
javascriptarraysjsonstringify

Javascript - convert array to stringify format


I have this array:

   array =  [
    {
        "name": "name",
        "value": "Olá"
    },
    {
        "name": "age",
        "value": "23"
    },
    {
        "name": "isVisible",
        "value": "1"
    }
]

And i need to convert it to this stringified format:

"{\"name\":\"Olá\",\"age\":123,\"isVisible\":true}"

I have made several attempts without luck.

My last attempt was this one:

array = array.map((p) => {
          return Object.values(p).join(':').replace(/\[/g, '{').replace(/]/g, '}').toString();
        }),

Any solutions?


Solution

  • Simply make a empty object, iterate over your array to populate that object, then JSON.stringify(obj) to get your result.

    Like this:-

    var obj = {};
    array =  [
        {
            "name": "name",
            "value": "Olá"
        },
        {
            "name": "age",
            "value": "23"
        },
        {
            "name": "isVisible",
            "value": "1"
        }
    ]
    
    for(let i of array) {
        obj[i.name] = i.value;
    }
    
    const str = JSON.stringify(obj);
    console.log(str);
    /*
    output : "{\"name\":\"Olá\",\"age\":123,\"isVisible\":true}"
    */