Reputation: 381
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
Upvotes: 0
Views: 413
Reputation: 6757
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])
});
Upvotes: 1