Pedram
Pedram

Reputation: 2621

Reading value of a key in an object using typescript

I have a array of objects and each object has two properties:

{key:count}

I am going to configure my chart and I should set the data source of the chart like below:

{meta: "unknown", value: [the count of unknown]},
{meta: "male", value: [the count of male]},
{meta: "female", value: [the count of female]}

Lets say my current array of objects is like:

[{"0":"10"}, {"1":"7"}, {"2":"9"}] in which 0 stands for unknown gender, 1 for male and 2 for female.

How can I set the value in the chart data in one line in such a way that it can find the count of each gender based on its key automatically from the array of objects.

Edit:

I have already written a method and it does the job:

public getKeyValue(data, key) {
    for (var i = 0; i < data.length; i++) {
        if (data[i].key == key)
            return data[i].count;
    }
    return 0;
}

However, I was wondering if there's a single line code solution like LINQ.

Upvotes: 1

Views: 1228

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164457

You can, but it's not pretty.

This will do the job:

data.map(item => item.key === key ? item.count : 0).reduce((previous, current) => previous + current);

(Check an example in playground)

But I wouldn't recommend using this instead of your code, because your code won't iterate over all the array elements if one was found to match the criteria, with my solution regardless of whether or not the criteria was met, there will be two iterations over all the array elements.

For example:

var key = "key3",
    data: { key: string, count: number}[] = [
        { key: "key1", count: 1 },  
        { key: "key2", count: 2 },  
        { key: "key3", count: 3 },  
        { key: "key4", count: 4 },  
        { key: "key5", count: 5 },
        //...
        { key: "key1554", count: 1554 }
    ];

The array (data) has the length of 1554, but you're looking for the 3rd element.
Your way will have 3 iterations and then return the value, my way will have 3108 iterations, one cycle (1554) for the map function and then another cycle for the reduce function.

Upvotes: 2

Related Questions