Reputation: 303
Hi I am trying to filter my JSON response to only get those values which are >=0.
My response is below :
{
"response": [{
"countryId": {
"id": "10050020025",
"idScheme": "externalId"
},
"processedDateTime": "2019-11-07 05:39:09",
"AAE": [{
"amount": "1000",
"currencyCode": "USD"
}],
"TAE": [{
"amount": "0",
"currencyCode": "USD"
}]
},
{
"countryId": {
"id": "10291520071",
"idScheme": "InternalId"
},
"processedDateTime": "2019-02-03 08:21:22",
"AAE": [{
"amount": "0",
"currencyCode": "USD"
}],
"TAE": [{
"amount": "-2001",
"currencyCode": "USD"
}]
}
]
}
I am trying to achieve :
{
"response": [{
"countryId": {
"id": "10050020025",
"idScheme": "externalId"
},
"processedDateTime": "2019-11-07 05:39:09",
"AAE": [{
"amount": "1000",
"currencyCode": "USD"
}]
},
{
"countryId": {
"id": "10291520071",
"idScheme": "InternalId"
},
"processedDateTime": "2019-02-03 08:21:22",
}
]
}
I am trying to use map & filter from es6 to achieve this but not good with don't know how i can do that. so far i am trying some hardcoded approach as.
const outputResponse = response
.map(value => value)
.filter(value => value.AAE[0].amount !== '0')
but it will remove whole object which don't have amount '0'.
Any help be appreciated.
Upvotes: 1
Views: 42
Reputation: 32145
You will just need an Array#map()
method call to map all the response
objects and remove the AAE
and TAE
or targeted keys
values which has amount
< 0:
let keys = ["AAE", "TAE"];
let result = data.response.map(val => {
keys.forEach(key => {
if (val[key] && val[key].some(x => +x.amount <= 0)) {
delete val[key];
}
});
return val;
});
Demo:
let keys = ["AAE", "TAE"];
let data = {
"response": [{
"countryId": {
"id": "10050020025",
"idScheme": "externalId"
},
"processedDateTime": "2019-11-07 05:39:09",
"AAE": [{
"amount": "1000",
"currencyCode": "USD"
}],
"TAE": [{
"amount": "0",
"currencyCode": "USD"
}]
},
{
"countryId": {
"id": "10291520071",
"idScheme": "InternalId"
},
"processedDateTime": "2019-02-03 08:21:22",
"AAE": [{
"amount": "0",
"currencyCode": "USD"
}],
"TAE": [{
"amount": "-2001",
"currencyCode": "USD"
}]
}
]
};
let result = data.response.map(val => {
keys.forEach(key => {
if (val[key] && val[key].some(x => +x.amount <= 0)) {
delete val[key];
}
});
return val;
});
console.log(result);
Upvotes: 1