Wiktor Kisielewski
Wiktor Kisielewski

Reputation: 437

Array map method for passing data from JSON

so I have this function that aims to map 'id' from JSON ('myObj') to an array:

function get_data () {
let myObj = (JSON.parse(this.responseText));
let id_array = myObj.map(item = () => {return item.id});
console.log(id_array);
}

console.log(myObj) gives me the expected results:

(10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {id: "774944", general: {…}, brand: {…}, images: {…}}
1: {id: "774945", general: {…}, brand: {…}, images: {…}}
...
9: {id: "738471", general: {…}, brand: {…}, images: {…}}
length: 10
__proto__: Array(0)

and it seems that get_data() function is working, but not exactly as expected. This is my id_array:

(10) [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined]
0: undefined
1: undefined
...
9: undefined
length: 10
__proto__: Array(0)

so as I see map function works by values are not read properly. What am I missing?

Upvotes: 2

Views: 1216

Answers (1)

Armin
Armin

Reputation: 134

ok so the line that is troublesome is

let id_array = myObj.map(item = () => {return item.id});

which reads as "assign an arrow function to the item variable, then insert that to map function to generate a new array. This, of course, does not make any sense, since the item in your arrow function would be undefined. following would be what you wanted

let id_array = myObj.map(item => {return item.id});

also, why not call myObj, myArray, to avoid confusion. Since it is actually an array. better yet use the shorthand

let id_array = myArray.map(item => item.id);

Upvotes: 3

Related Questions