2

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?

2
  • btw, why an assignment to a global variable with item = () => {return item.id}? Commented Jun 13, 2019 at 20:03
  • 6
    Get rid of the = (). Just item => {return item.id}. Or with an implicit return: item => item.id. Commented Jun 13, 2019 at 20:07

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

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.