I have an object that looks like this:
var obj = {
"array1": [
{"label": "something1", "ref": "option2a"},
{"label": "something2", "ref": "option2b"},
{"label": "something3", "ref": "option2a"},
{"label": "something4", "ref": "option2a"},
{"label": "something5 is the longest", "ref": "option2a"}
],
array2: [
"arrayItem1",
"array Item 2"
]
}
This object contains arrays of objects and arrays of strings. I would like to traverse through each object that has a label and return the longest label. In the previous example, the expected output id:
"something5 is the longest".
I have tried the following:
function getLongest(object, key) {
return Object.values(object).reduce((l, v) => {
if (object.hasOwnProperty(key)) {
if (key in v)
return Math.max(l, v[key].length);
if (v && typeof v === 'object')
return Math.max(l, getLongest(v, key));
return l;
}
}, 0);
}
However this gives me an error because it cannot find the property label for the items in array2.