我正在研究 React Native 项目。
其中,我从 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());
关于javascript - 如何在javascript中过滤数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55267613/