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?

1

1 Answer 1

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}"
*/
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. You pointed me in the right direction. I have transformed you for loop in a map and iterate over it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.