How to get the object key it has the value - javascript

I have a filter component which user can choose any data to filter so I store this data in state.when I want to create a params for query some of the field not choosen by user I only wanna get the one which has value here is the code ;
function createParams(params = {}) {
let result = "?";
for (let key in params) {
result += `${key}=${params[key]}&`;
}
return result;
}
export async function callApi(params) {
const parameters = createParams(params);
try {
const response = await fetch(URL+ parameters);
const res = await response.json();
return res;
} catch (error) {
console.error(error)
throw error;
}
}
export const requestProperties = (params) => callApi(params);
const requestedParams = {type:"Fiat", model:"500", color:""};
I only want to get the type and model because it has been choosen by user to filter. I dont wanna include the colour
Thank you..:)

You can take entries and then filter out the records.
var requestedParams = {type:"Fiat", model:"500", color:""};
var result = Object.fromEntries(Object.entries(requestedParams).filter(([k,v])=>v));
console.log(result);

You can destructure the object if you only want to exclude one key-value pair
const requestedParams = {type:"Fiat", model:"500", color:""};
const exclude = 'color';
const {[exclude]: remove, ...rest} = requestedParams;
console.log(rest);
If you have multiple key-value pairs that you want to exclude, you can use reduce function
const requestedParams = { type: "Fiat", model: "500", color: "" };
const res = Object.entries(requestedParams).reduce((acc, curr) => {
return curr[1] ? (acc[curr[0]] = curr[1], acc) : acc;
}, {});
console.log(res);

Related

How to change field from return response in api

This is the result of response from api
what I want is to change the field return like
_id to id
existing code
WorkflowApi.getTransactionLog().then(logs => {
const newLog = {
...logs,
'id': logs._id
}
}
current result
If you just want to change one specific item, you need to choose it by key - as they are numeric you'll have to use square bracket notation
WorkflowApi.getTransactionLog().then(logs => {
const newLog = {
...logs[43],
'id': logs[43]._id
}
}
If you want to change all of them you'll need to loop
WorkflowApi.getTransactionLog().then(logs => {
const newLogs = Object.fromEntries(Object.entries(logs).map( ([k,v]) => {
return [k, {
...v,
'id': v._id
}]
}))
}
For removing a key I would suggest something like this:
const objectWithoutKey = (object, key) => {
const {[key]: deletedKey, ...otherKeys} = object;
return otherKeys;
}
console.log(objectWithoutKey({_id:123,id:123},"_id"))

Add documentID of fetched document to array in firebase cloud function

I have a cloud function that "Joins" data from a list of documents in a collection.
I then return the result as an array, but I want to return the documentId as well (doc.id) in the list that i return.
How can i do that?
const restData = [];
//const userId = ctx.auth.uid;
const userId = 'dHAP1CNN6LhJWddQoTqyIkqIjhB2'; // !!! TEST ONLY
const all = await db.collection(`/customers/${userId}/lunch_cards`).listDocuments().then((snapshot) => {
snapshot.forEach(doc => {
const nextData = db.collection(`/restaurants`).doc(doc.id).get();
const newData = {...nextData, documentId: doc.id}; <-- This does not work only documentId isout in newData
console.log(util.inspect(newData));
restData.push(nextData);
console.log(doc.id);
});
});
const snaps = await Promise.all(restData);
const responseArray = snaps.map((s) => {return s.data()});
return responseArray;
I solved it!
Solution:
Just adding a new string to the array :)
const responseArray = snaps.map((s) => {
const snapData = s.data();
if (snapData) {
snapData['id'] = s.id;
}
return snapData;
});

Storing MongoDB document inside a Node.js array and return it

I try to get specific documents from MongoDB with Node.js and insert them into array.
const getStockComments = async (req) => {
const stockname = req.params.stockName;
var comments = [];
var data = [];
const stock = await stockModel.findOne({ name: stockname });
comments = stock.comments;
comments.forEach(async (commentId) => {
const comm = await commentModel.findOne({ _id: commentId });
data.push(comm);
console.log(data); // This returns the data in loops, because its inside a loop.
});
console.log(data); // This not returns the data and i don't know why.
return data;
};
The first console.log(data) returns the same data a lot of times because its inside a loop.
But the second console.log(data) dosen't returns the data at all.
What I'm doing wrong?
Instead of using loop , you can use $in operator to simplify things .
const getStockComments = async (req) => {
const stockname = req.params.stockName;
var comments = [];
var data = [];
const stock = await stockModel.findOne({ name: stockname });
comments = stock.comments;
commentModel.find({ _id: { $in: comments } }, (err, comments) => {
data = comments;
});
console.log(data);
return data;
};

How can I retrieve the data from Promise object in React?

Here is my code snippet for parsing application data:
async function parseApplication(data: Application) {
const fieldGroupValues = {};
for (const group of Object.keys(data.mappedFieldGroupValues)) {
const groupValue = data.mappedFieldGroupValues[group];
for (const fieldName of Object.keys(groupValue.mappedFieldValues)) {
const { fieldValue } = groupValue.mappedFieldValues[fieldName];
}
return fieldGroupValues;
}
But I receive data as Promise object, how can I retrieve data from Promise?
In you example you are combining both of await and .then(), I would use only one of them.
Preferably await as the following:
try {
const dict = await getDictionaryByKey(fieldValue.value.entityDefinitionCode);
const dictItem = dict.find((item) => fieldValue.value.entityId === item.code);
acc[fieldName] = dictItem ? dictItem.text : fieldValue.value.entityId;
} catch (err) {
acc[fieldName] = fieldValue.value.entityId;
}

Create object with only defined properties

I have a function which returns an object with properties only which are defined.
How to refactor the function so that I don't need to make if clauses for every parameter value? There must be more elegant way to do this.
const getQuery = ({ foo, bar, zoo }) => {
const query = {};
if (foo) {
query.foo = foo;
}
if (bar) {
query.bar = bar;
}
if (zoo) {
query.zoo = zoo;
}
return query;
}
I would do something like
function getQuery(obj){
// filter the accepted keys
var filtered = Object.keys(obj).filter((k) => ~["foo", "bar", "baz"].indexOf(k))
// construct new object with filtered keys
var query = {}
filtered.forEach((k) => query[k] = obj[k])
return query
}
Here's a basic function that will copy only properties provided in the wantedProps array. It will not mutate the original object.
let filterProperties = (originalObject = {}, wantedProps = []) =>
{
let filteredObject = {};
wantedProps.forEach( val => filteredObject[val] = originalObject[val] );
return filteredObject;
}
If you're just trying to filter out undefined vals then you could do:
obj => {
let newObject = {}
Object.keys(obj).forEach(key => {
if(obj[key] !== undefined) newObject[key] = obj[key];
})
return newObject;
}

Categories

Resources