0

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'
          );
1
  • do you mean an object? Commented Nov 18, 2017 at 11:12

3 Answers 3

2

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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"}

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.