Reputation: 18346
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(
15 => 'music',
103 => 'movie',
214 => 'book'
);
Upvotes: 0
Views: 47
Reputation: 50346
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)
Upvotes: 0
Reputation: 124804
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"}
Upvotes: 1
Reputation: 386848
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);
Upvotes: 2