javascript - 如何在javascript中过滤数据
问题描述
我正在处理本机项目。
在那,我从 api 获取多个数据,如下所示。
{
Value: "895"
Return: "2"
Return1: "0.20"
Return3: "0.40"
Return5: "0.60"
Return10: "0.50"
StartDate: "2019-06-13"
}, {
Value: "900"
Return: "4"
Return1: "0.10"
Return3: "0.40"
Return5: "0.70"
Return10: "0.90"
StartDate: "2019-06-14"
},
但是,我试图将所有返回数据带到某个返回数组,我需要将每个数据索引显示到平面列表中。但是,在这里我很困惑如何将它放入另一个数组,因为返回键在每个索引的键的末尾都有 1、3、5 等。
const ValuesData = [];
if (ReturnsData) {
ReturnsData.map((item, index) => {
ValuesData.push({
`${ReturnsData[index].Return`${index}`}`,
});
});
}
谁能建议我如何将 Return(1,3,5,10) 数据放入数组中?
解决方案
startWith
与getOwnPropertyNames
或一起使用Object.keys( your_object )
。
var apiData = [{
Value: "895",
Return: "2",
Return1: "0.20",
Return3: "0.40",
Return5: "0.60",
Return10: "0.50",
StartDate: "2019-06-13",
}, {
Value: "900",
Return: "4",
Return1: "0.10",
Return3: "0.40",
Return5: "0.70",
Return10: "0.90",
StartDate: "2019-06-14",
}]
/* All values of each key thats starts with "Return" in flat array */
const valuesFlat = []
apiData.map( (it, idx) =>
Object.getOwnPropertyNames(it).filter( prop => prop.startsWith("Return") )
.map( name => apiData[idx][name] )
.forEach( its => valuesFlat.push(its) )
)
console.log( "Flat values" )
console.log( valuesFlat )
/* All values of each key thats starts with "Return", not flat array */
const values = apiData.map( (it, idx) =>
Object.getOwnPropertyNames(it).filter( prop => prop.startsWith("Return") )
.map( name => apiData[idx][name] )
)
console.log("Values")
console.log(values)
const indexes = apiData.map( (it, idx) =>
Object.getOwnPropertyNames(it)
.map( (prop, idxs) => { if(prop.startsWith("Return")) return idxs} )
.filter( prop => prop != undefined )
)
console.log("indexes")
console.log( indexes )
const indexesFlat = []
apiData.forEach( (it, idx) =>
Object.getOwnPropertyNames(it)
.map( (prop, idxs) => { if(prop.startsWith("Return")) return idxs} )
.filter( prop => prop != undefined )
.forEach( it => indexesFlat.push(it) )
)
console.log("Flat indexes")
console.log( indexesFlat )
const flatPropsWithValues = []
apiData.map( (it, idx) =>
Object.getOwnPropertyNames(it)
.filter( prop => prop.startsWith("Return") )
.forEach( prop => flatPropsWithValues.push( { prop: prop, value: apiData[idx][prop] } ) )
)
console.log("Flat props with values")
console.log( flatPropsWithValues )
Log.d(TAG, "runON" + Thread.currentThread().getName());
推荐阅读
- xaml - 用户取消选择时继续突出显示单元格
- python - 图片下载器
- mysql - 如果我们按同一字段的不同值进行搜索,可以用 SQL 查询中的较短条件替换 OR
- security - 在基于 OAuth2 的身份验证中,状态参数可以防止什么样的 CSRF 攻击?
- android - Robotium Eclipse 是否可以进行黑盒测试?
- python - For循环,如何通过特殊条件来属性列中的值
- azure - 管理员如何仅为应用注册授予特定用户的访问权限?
- python - Clustermap Seaborn 掩盖了矩阵的上对角线,固定每个“单元格”的大小并删除连接每个单元格的线
- java - 我们可以合并两个安卓源并使用产品风格吗?
- azure-keyvault - 如何仅在 ARM 模板中更改或检查它是否存在时更新 Azure Key Vault 中的机密