简体   繁体   English

用于从JSON传递数据的数组映射方法

[英]Array map method for passing data from JSON

so I have this function that aims to map 'id' from JSON ('myObj') to an array: 所以我有一个旨在将JSON('myObj')中的'id'映射到数组的函数:

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: console.log(myObj)给了我预期的结果:

(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. 似乎get_data()函数正在运行,但不完全符合预期。 This is my id_array: 这是我的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 它的内容为“将箭头函数分配给item变量,然后将其插入到map函数中以生成新数组。这当然没有任何意义,因为箭头函数中的项目将是未定义的。你想要什么

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

also, why not call myObj, myArray, to avoid confusion. 另外,为什么不调用myObj,myArray以避免混淆。 Since it is actually an array. 由于它实际上是一个数组。 better yet use the shorthand 最好使用速记

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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