Richard Roberts Richard Roberts - 3 months ago 7
Javascript Question

Turn Array objects into JSON using javascript or jquery

I have dynamic data coming into my website like this:

[{
"itemOne": {
"url": "www",
"name": "Bob"
},
"itemTwo": {
"url": "www",
"name": "fred"
}
}]


Using jQuery or Javascript, I would like to turn this data into JSON, so it would be structured like this:

"products": {
"itemOne": {
"url": pageUrl,
"name": productName
},
"itemTwo": {
"url": pageUrl,
"name": productName,
}
}


Is this possible? If so, how would I go about it?

Answer

To achieve this you can just take the first object from the array and set it as the value of the product property of a new object. If you need to turn this object in to JSON, call JSON.stringify on the result. Try this:

var arr = [{
  "itemOne": {
    "url": "www",
    "name": "Bob"
  },
  "itemTwo": {
    "url": "www",
    "name": "fred"
  }
}]

var obj = {
  products: arr[0]
}

var json = JSON.stringify(obj);
console.log(json);

Comments