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
1
  • 3
    You can't have duplicate keys in an object, the last one wins. In this case third overrides second Commented Sep 19, 2019 at 10:38

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

7 Comments

In my real world data that is a comment and for each new comment that is added a new duplicate key is added.
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.
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 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.
Where are you getting this data from? @JoeBerg
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.
|

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.