I am working on an API, and I want to return values based on some input I receive. For example, here is a body sample input
JavaScript
x
4
1
{
2
"fields": ["account", "id"]
3
}
4
Based on the fields array, I want my API to return only those values. Here is an example of the API implementation
JavaScript
1
18
18
1
2
const {fields} = req.body
3
const result = makeDataConversion(data)
4
const objKeys = result.map((i) => Object.keys(i)) // returns the keys from the arr of object of the result variable
5
6
// I am comparing the values in the fields array with the keys gotten from objKeys variable
7
if (fields) {
8
fields.forEach((items) => {
9
objKeys.forEach((item) => {
10
if (items.indexOf(item) > -1) {
11
const s = result.filter(item => {}) // stuck here
12
res.json({ s })
13
}
14
})
15
})
16
}
17
18
So the part where I indicate stuck here I want to loop through the result array of objects and return only the properties that match the values gotten from the field’s array.
Here is a typical API Response
JavaScript
1
13
13
1
status: true
2
message: "Data retrieved successfully"
3
data: [
4
{
5
"account": "john doe",
6
"date_registered": "10/10/1994",
7
"amount": "50000",
8
"isActive": "false"
9
"id": "34"
10
}
11
]
12
13
So my final API Response
should be
JavaScript
1
4
1
status: true
2
message: "Data retrieved successfully"
3
data: [{"account": "john doe", "id": "34"}]
4
How do I go about this please.
Thank you
Advertisement
Answer
JavaScript
1
44
44
1
const apiResponse = {
2
status: true,
3
message: "Data retrieved successfully",
4
data: [
5
{
6
"account": "john doe",
7
"date_registered": "10/10/1994",
8
"amount": "50000",
9
"isActive": "false",
10
"id": "34"
11
},
12
{
13
"account": "john doe 2",
14
"date_registered": "10/10/1994",
15
"amount": "50000",
16
"isActive": "false",
17
"id": "35"
18
}
19
]
20
};
21
22
const fieldsInput = {
23
"fields": ["account", "id"]
24
};
25
26
const getFinalResult = (response) => {
27
28
const data = response.data.map(item => {
29
const result = {};
30
fieldsInput.fields.forEach(field => {
31
result[field] = item[field];
32
})
33
return result;
34
});
35
36
return {
37
response,
38
data
39
}
40
};
41
42
const finalResult = getFinalResult(apiResponse);
43
44
console.log(finalResult);
Just doing a .map()
over your response and inside that map just iterate over your fields and returned the mapped result based on those fields.