JS Multidimensional array search by value

Ask a question+
0

Following is the js array I have

[{"tag_id":10,"package_count":62,"destination_country":"IN","tag_name":"Fibroidsssssssssssss"},{"tag_id":21,"package_count":22,"destination_country":"IN","tag_name":"Laparoscopic Myomectomy for Fibroids\r"},{"tag_id":46,"package_count":3,"destination_country":"IN","tag_name":"Ear reshaping\r"},{"tag_id":49,"package_count":6,"destination_country":"IN","tag_name":"Gynecomastia\r"},{"tag_id":93,"package_count":19,"destination_country":"IN","tag_name":"TLIF - Transforaminal Lumbar Interbody Fusion\r"}]

I want package_count from array by tag_name
Like package_count for tag_name Gynecomastia

add comment

1 Answer

1

You could use Array.filter() for this:

const getPackageCount = (arr,tag) => {
    return arr.filter((item) => {
        return item['tag_name'] == tag;
    })[0]['package_count']
}

// The way above still makes a function, but if you want it to be in the regular format, you could do it like this:
function getPackageCount(arr,tag) {
    return arr.filter((item) => {
        return item['tag_name'] == tag;
    })[0]['package_count']
}

In you array, you have some of the tag_name values end with \r, is this on purpose? If so, when using that function you will have to include the \r in the input tag name:

getPackageCount(tagArray, "Gynecomastia\r")
Batman 310
add comment

Your Answer