简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM