#Javascript Parsing HW Question

53 messages · Page 1 of 1 (latest)

unborn aspen
#

This is the teacher's solution to a parsing problem. I understand all of the code until it reaches the point with the forEach. Could someone explain that for me? Specifically the obj[headers[idx]] = val.

let csvData = "name,age\nFrodo,50\nSam,38\nMerry,36\nPippin,26";
//Headers: name, age.
//Row example: Frodo, 50

function csvConverter(data) {

  //Split csvData into rows based on each newline character.

  let rows = csvData.split('\n');

  //Split the first row or headers into individual strings based on
  //the comma character.

  let headers = rows[0].split(',') //[name, age]

  let result = [];

  //Iterate over every content row.
  for (let i = 1; i < rows.length; i++) {

    let obj = {};

    let data = rows[i].split(',') // Ex. [ 'Frodo', 50 ]

    data.forEach((val, idx) => {
      obj[headers[idx]] = val
    })

    result.push(obj);
  }
  return result
}

console.log(csvConverter(csvData));
proper sky
#

headers[idx] This gets the element from headers at index idx. Since your teacher is using a for each loop, by doing headers[idx], they are getting each element from headers.

Let's say idx is 0, headers[idx] will be 'name' and by doing obj[headers[idx]], they are saying obj['name'] = Frodo. So, they are creating a key called name with value of Frodo.

#

@unborn aspen

unborn aspen
#

How is idx able to loop through the array? I thought only i could do that.

proper sky
#

So, it is sort of similar to i

unborn aspen
#

I'm still lost. I understand forEach is basically a loop and this is adding something to an empty object.

#

I don't understand why idx is on headers or why they're set to equal val.

proper sky
#

data.forEach((val, idx) This part loops over data (which is ['Frodo', 50]). On the first iteration,
val = Frodo,
idx = 0 and
headers = ['name', 'age']

Now,
headers[idx] = headers[0] = 'name'and
obj[headers[idx]] = val = obj['name'] = 'Frodo'

obj looks like {'name': 'Frodo'} after the first iteration

unborn aspen
#

I had completely forgotten Data itself is a loop.

#

I keep strugging to remember when those come up.

proper sky
unborn aspen
#

Oh, because of split.

proper sky
#

correct

unborn aspen
#
data.forEach((val, idx) => {

      obj  [headers   [idx]    ] = val

    }
)

    result.push(obj);
#

Obj = {}.

headers = rows[0].split(',') //[name, age]

idx = 0

#

It's adding headers into object.
Headers has idx (which = 0) in it.

#

Headers is an array.

proper sky
#

I am not sure what you need help with 😅

unborn aspen
#

I'm trying to make it legible for myself.

#

Why is this all equal to val?

proper sky
#

You are basically making key value pair by setting obj[headers[idx] ] = val. Then, if you want to access the name of the first student from result, you would do let first_student_name = result[0]['name']

#

The result array contains multiple students with their names and age. You can loop over each student and print their name and age like for(let i = 0; i < result.length; i++){ console.log("Name: " + result[i]["name"]) console.log("Age: " + result[i]["age"]) }

unborn aspen
#

Does this seem like a beginner problem?

proper sky
#

I mean it takes some practice to see the whole picture and see how things are interacting with each other. So, it can be a bit hard to grasp, but it will become easier with practice.

unborn aspen
#

I still can't. I even used a vizualizer.

#

I guess Val still seems really intangible.

#

It only gets used once, when you're changing what it's equal to.

#

It never gets called again or placed outside of being an argument, but somehow it has this important role?

proper sky
#

Do you know how objects work in js?

unborn aspen
#

I think I have a basic understanding.

#

I'm sure I'm missing something.

proper sky
#

how would you create a key value pair in an object?

unborn aspen
#

Oh...

#

That's what this is.

#

obj[key] = value.

#

I wasn't looking at it like that at all.

#

Wait, so you can insert a key and value at the same time?

proper sky
unborn aspen
#

I thought it had to be separate for some reason. I see.

#

That's a breakthrough. Now I can reframe everything.

#

I understand it better now, but how does this end up making a key for age?

#

I'm guessing it's looping somehow through forEach?

proper sky
unborn aspen
#

So both val and idx in this forEach are iterating, right?

#

I get it, I get it.

#

This has reminded me how Objects work again and also finally shown me what forEach does.

#

Thank you. I think I have a pretty good understanding now. My only concern is how I'd know in the future to use this structure.

#

data.forEach((val, idx) => { obj[headers[idx]] = val; is pretty weird because headers was just kind of inserted.

proper sky
unborn aspen
#

Is this a common structure used for parsing csv?

proper sky
#

yeah, I have used it too