我有以下json。从下面的json中,我只需要数组形式的每个项目的PartNumber。谁能帮忙使用过滤器做到这一点?
下面是我的代码。在控制台日志中,仅获取第一项的部件号
state = {
data: MYResult.Products || [],
partNumbers: []
};
componentDidMount(){
const allPartNumbers = this.state.data.filter(partnumbers =>
this.state.data.PartNumber);
console.log(allPartNumbers)
}
"Products": [
{
"PartNumber": "ALM-GN001",
"ProductName": "GNSS Filter-LNA Front-End Module",
"productline": "GPS/GNSS Wireless Amplifiers",
"AV_47_Frequency_GHz": "1.575",
"AV_47_NF": ""
},
{
"PartNumber": "ALM-GP001",
"ProductName": "GPS Filter-LNA-Filter Front-End Module",
"productline": "GPS/GNSS Wireless Amplifiers",
"AV_47_Frequency_GHz":"1.565 - 1.606",
"AV_47_NF": ""
},
{
"PartNumber": "ALM-GA001",
"ProductName": "High-Gain, Low-Current LNA with Variable Current and Shutdown Function",
"productline": "GPS/GNSS Wireless Amplifiers",
"AV_47_Frequency_GHz": "1.606",
"AV_47_NF": "0.97"
},
{
"PartNumber": "ALM-GN002",
"ProductName": "GNSS LNA-Filter Front-End Module with Optional Differential Outputs",
"productline": "GPS/GNSS Wireless Amplifiers",
"AV_47_Frequency_GHz": "1.565",
"AV_47_NF": "0.97"
}
]
答案 0 :(得分:1)
filter
将创建一个新数组,其中包含所有从函数返回真实值的元素。您想改用map
,而只需拔出PartNumber
属性。
示例
const products = [
{
PartNumber: "ALM-GN001",
ProductName: "GNSS Filter-LNA Front-End Module",
productline: "GPS/GNSS Wireless Amplifiers",
AV_47_Frequency_GHz: "1.575",
AV_47_NF: ""
},
{
PartNumber: "ALM-GP001",
ProductName: "GPS Filter-LNA-Filter Front-End Module",
productline: "GPS/GNSS Wireless Amplifiers",
AV_47_Frequency_GHz: "1.565 - 1.606",
AV_47_NF: ""
},
{
PartNumber: "ALM-GA001",
ProductName:
"High-Gain, Low-Current LNA with Variable Current and Shutdown Function",
productline: "GPS/GNSS Wireless Amplifiers",
AV_47_Frequency_GHz: "1.606",
AV_47_NF: "0.97"
},
{
PartNumber: "ALM-GN002",
ProductName:
"GNSS LNA-Filter Front-End Module with Optional Differential Outputs",
productline: "GPS/GNSS Wireless Amplifiers",
AV_47_Frequency_GHz: "1.565",
AV_47_NF: "0.97"
}
];
const result = products.map(product => product.PartNumber);
console.log(result);
答案 1 :(得分:0)
这不是筛选操作。只需使用map
而不是filter
。 (用地图替换过滤器)
答案 2 :(得分:0)
Array.filter()
用于创建一个新数组,其元素满足filter(() => condition)
方法中的回调函数中给出的条件。
您可以按以下方式使用reduce:
const productsNumbers = products.reduce((accum, product) => {
accum.push(product.PartNumber);
return accum;
}, []);
在这种情况下,productsNumbers[]
将具有以下含义:
`productsNumbers = []