0

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?

André Castro
  • 1,527
  • 6
  • 33
  • 60
  • 2
    [sometimes reading the doc can be useful... `JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) – Mister Jojo Nov 04 '22 at 17:38

1 Answers1

2

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}"
*/
Abhay Bisht
  • 185
  • 7