I was wondering how I can filter the values "tags" in the json above using an arrow function:
const ttag = [{
"code": 795302828,
"code_integration": "123",
"company": "ACME LTD",
"phone": "135575788",
"tags": [{"tag": "companyAA"},
{"tag": "companyBB"},
{"tag": "companyCC"},
{"tag": "companyDD"}
],
"status": "Y"
}]
const onlyTags = ttag.filter(f => f.tags)
console.log(onlyTags)
expected result: ['companyAA', 'companyBB', 'companyCC', 'companyDD']
First of all, that's not how filter
method works. Filter
returns an array with values that are true
for function passed as the argument. More you can read here.
You could use map
& flatMap
, like this:
ttag.flatMap(f => f.tags.map(t => t.tag));
map
returns array of values specified in the passed method. flatMap
does the same, but if the result is an array it flattens it, so result is an array of strings instead of an array of arrays of strings.
flatMap
is not supported in Internet Explorer, but it's already unsupported browser so I wouldn't bother.