Skip to content Skip to sidebar Skip to footer

How To Convert Json Output To Array In Jquery

I have this JSON output: [{'id':'15','title':'music'},{'id':'103','title':'movie'},{'id':'214','title':'book'}] How can I convert it to an array like in Javascript: items = array(

Solution 1:

You could use Object.assign with a destructed object and by building a new object.

var array = [{ id: "15", title: "music" }, { id: "103", title: "movie" }, { id:"214", title: "book" }],
    object = Object.assign(...array.map(({ id, title }) => ({ [id]: title })));
    
console.log(object);

Solution 2:

You can use reduce(...):

var arr = [{"id":"15","title":"music"},{"id":"103","title":"movie"},{"id":"214","title":"book"}];
var obj = arr.reduce((acc, o) => { acc[o.id] = o.title; return acc; }, {});
console.log(obj);
// prints: {15: "music", 103: "movie", 214: "book"}

Solution 3:

Seems you are looking for an object like this

var x = [{
  "id": "15",
  "title": "music"
}, {
  "id": "103",
  "title": "movie"
}, {
  "id": "214",
  "title": "book"
}];
let temp = {};
x.forEach(function(item) {
  temp[item.id] = item.title
})
console.log(temp)

Post a Comment for "How To Convert Json Output To Array In Jquery"