0

I'm trying to return only the first object's (that) string from an array. In my example when I loop it will return only the string from the third option.

I'd like for it to return only the second option e.g. the first object named that.

I thought it would work like this:

data[i].that[0]

But it will return only the first letter.

var data = [{  
   "this":"first",
   "that":"second",
   "that":"third",
},{  
    "this":"first",
    "that":"second",
    "that":"third",
}]

data.forEach(function (value, i) {
     console.log(data[i].that)
});

Current:

third
third

Expected:

second
second
Joe Berg
  • 381
  • 3
  • 16

1 Answers1

1

Your data is modeled wrong. You can't have duplicate keys in a JavaScript object.

You can however remodel it to the following, to achieve what you want (calling it with data[i].that[0]):

var data = [{  
   "this":"first",
   "that": ["second", "third"]
},{  
    "this":"first",
    "that":["second", "third"]
}]

data.forEach(function (value, i) {
     console.log(data[i].that[0])
});
MauriceNino
  • 6,214
  • 1
  • 23
  • 60
  • In my real world data **that** is a comment and for each new comment that is added a new duplicate key is added. – Joe Berg Sep 19 '19 at 10:42
  • then add them to a `comments` array, just like I did in the example. What you are doing will not work, so you need to think about changing the way you model your data. – MauriceNino Sep 19 '19 at 10:43
  • First of all, thanks a lot for the help, I understand why it's not working now. Unfortunately I won't be able to restructure the data though, I can only work with what I have. Is there any other work-around I could try? I read some about a solution here https://stackoverflow.com/questions/30842675, where the user mentioned a way to parse data as text and return as a string. Unfortunately I cannot use jQuery so I couldn't try out the example. If you have any idea how to rewrite it in vanilla JS I would be really thankful. – Joe Berg Sep 19 '19 at 11:11
  • Where are you getting this data from? @JoeBerg – MauriceNino Sep 19 '19 at 11:16
  • It is used where I work at by another team, but my team can also benefit from some some of this data. The other team uses this data differently so there's currently no script that we could use. In our team we need to check if the comments contains some of the IDs related to items that we work on. So I am passing the mentioned data into a table and checking if one of the comments contains one of our IDs. The ID will always be listed in the first comment, so if I could either get both of the comments or only the first it would work for us. – Joe Berg Sep 19 '19 at 11:39
  • Sorry, but I don't quite understand, what comments and IDs are for you. Can you please elaborate a bit more? @JoeBerg – MauriceNino Sep 19 '19 at 11:46
  • In the data above "that":"second" would be "comment":"the id", and "that":"third" would be "comment":"not useful text". – Joe Berg Sep 19 '19 at 12:41