user3180997 :
What is the best way to "filter" through an object? I have an example object that looks like:
const response = {
"example-feed": [
{
"money": {
"amount": 2588
},
"sourcemoney": {
"amount": 2588
},
"direction": "OUT"
},
{
"money": {
"amount": 2925
},
"sourcemoney": {
"amount": 2925
},
"direction": "IN"
},
{
"money": {
"amount": 1921
},
"sourcemoney": {
"amount": 1921
},
"direction": "OUT"
},
{
"money": {
"amount": 1467
},
"sourcemoney": {
"amount": 1467
},
"direction": "IN"
},
]
}
What is the best way to "filter" through it to remove any objects that have the key-value pairing of "direction": "IN"
?
For example, I would like to remove the two objects that have a direction set to IN, so the new object becomes:
const response = {
"example-feed": [
{
"money": {
"amount": 2588
},
"sourcemoney": {
"amount": 2588
},
"direction": "OUT"
},
{
"money": {
"amount": 1921
},
"sourcemoney": {
"amount": 1921
},
"direction": "OUT"
},
]
}
Within an array, I know you can use the filter
functionality? Curious to understand what the best practise is here to try and achieve the above?
StepUp :
The best practice is to use methods which are designed to make filtering:
response['example-feed'] = response['example-feed'].filter(f => f.direction != 'IN');
filter method works with arrays, so you need to filter array, not an object.
An example:
const response = {
"example-feed": [
{
"money": {
"amount": 2588
},
"sourcemoney": {
"amount": 2588
},
"direction": "OUT"
},
{
"money": {
"amount": 2925
},
"sourcemoney": {
"amount": 2925
},
"direction": "IN"
},
{
"money": {
"amount": 1921
},
"sourcemoney": {
"amount": 1921
},
"direction": "OUT"
},
{
"money": {
"amount": 1467
},
"sourcemoney": {
"amount": 1467
},
"direction": "IN"
},
]
};
response['example-feed'] = response['example-feed'].filter(f => f.direction !=
'IN');
console.log(response)
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=336643&siteId=1