首页 > 解决方案 > 如何在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) 数据放入数组中?

标签: javascriptarrayssortingfilter

解决方案


startWithgetOwnPropertyNames或一起使用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());


推荐阅读