这是我的数据:
{
"productGroups": [
{
"selectedProducts": [
{ "productPricing": { "recurringFee": {}, "oneTimeFee": {} }, "id": "610e99f9b13b4126a9e07e36" }
]
},
{
"selectedProducts": [
{ "productPricing": { "recurringFee": {}, "oneTimeFee": {} } }
]
},
{
"selectedProducts": [
{ "productPricing": { "recurringFee": {}, "oneTimeFee": {} } }
]
}
]
}
如果没有selectedProducts.id,我想删除数组元素
所以结果应该是:
{
"productGroups": [
{
"selectedProducts": [
{ "productPricing": { "recurringFee": {}, "oneTimeFee": {} }, "id": "610e99f9b13b4126a9e07e36" }
]
}
]
}
这是我尝试过的:
const filteredData = {
productGroups: data.productGroups.map(productGroup => {
const selectedProduct = productGroup.selectedProducts?.filter(product => product.id);
return selectedProduct;
}),
};
我的结果是错误的,我得到的结果与空数组:
{
"productGroups": [
[
{ "productPricing": { "recurringFee": {}, "oneTimeFee": {} }, "id": "610e9a5eb13b4126a9e07e37" }],
[],
[]
]
}
let data = {
"productGroups": [
{
"selectedProducts": [
{ "productPricing": { "recurringFee": {}, "oneTimeFee": {} }, "id": "610e99f9b13b4126a9e07e36" }
]
},
{
"selectedProducts": [
{ "productPricing": { "recurringFee": {}, "oneTimeFee": {} } }
]
},
{
"selectedProducts": [
{ "productPricing": { "recurringFee": {}, "oneTimeFee": {} } }
]
}
]
};
const filteredData = {
productGroups: data.productGroups.filter(productGroup => {
const selectedProduct = productGroup.selectedProducts.filter(product => product.id);
return selectedProduct.length;
}),
};
console.log(JSON.stringify(filteredData))
我是这样做的:
const filteredData = {
productGroups: data.productGroups.filter(productGroup => {
return (productGroup.selectedProducts.filter((product) => (product.id !== undefined && product.id != '') ? true: false)).length;
}),
};