Object 使用typescript读取对象中键的值
我有一个对象数组,每个对象有两个属性:Object 使用typescript读取对象中键的值,object,typescript,Object,Typescript,我有一个对象数组,每个对象有两个属性: {key:count} 我将配置我的图表,我应该设置图表的数据源,如下所示: {meta: "unknown", value: [the count of unknown]}, {meta: "male", value: [the count of male]}, {meta: "female", value: [the count of female]} 假设我当前的对象数组如下所示: [{“0”:“10”},{“1”:“7”},{“2”:“9”}]
{key:count}
我将配置我的图表,我应该设置图表的数据源,如下所示:
{meta: "unknown", value: [the count of unknown]},
{meta: "male", value: [the count of male]},
{meta: "female", value: [the count of female]}
假设我当前的对象数组如下所示:
[{“0”:“10”},{“1”:“7”},{“2”:“9”}]
其中0代表未知性别,1代表男性,2代表女性
如何在一行中设置图表数据中的值,使其能够根据对象数组中的键自动找到每个性别的计数
编辑:
我已经编写了一个方法,它可以完成以下工作:
public getKeyValue(data, key) {
for (var i = 0; i < data.length; i++) {
if (data[i].key == key)
return data[i].count;
}
return 0;
}
publicGetKeyValue(数据,键){
对于(变量i=0;i
但是,我想知道是否有像LINQ这样的单行代码解决方案。您可以,但它并不漂亮 这将完成以下工作:
data.map(item => item.key === key ? item.count : 0).reduce((previous, current) => previous + current);
()
但是我不建议使用这个来代替您的代码,因为如果发现一个数组元素与标准匹配,那么您的代码将不会迭代所有数组元素。对于我的解决方案,无论是否满足标准,都会对所有数组元素进行两次迭代
例如:
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 }
];
数组(data
)的长度为1554
,但您正在查找第三个元素。您的方式将有3次迭代,然后返回值,我的方式将有3108次迭代,一个周期(1554)用于
map
函数,然后另一个周期用于reduce
函数