dynamic loop base on object key javascript - javascript

I have a list, I have a search bar for filtering,
handleSearch = e => {
const q = e.target.value
if(q){
const filtered = this.state.data.filter(o => {
return o['name'].includes(q)
})
this.setState({
data: filtered
})
}else{
this.setState({
data: this.state.source
})
}
}
the problem with this method is that I hardcoded o['name'] which is a problem if my list has multiple property.
https://codesandbox.io/s/420lxz97r4

You can use Object.keys and Array.some:
return Object.keys(o).some(e => o[e].includes(q))

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"))

Vuejs Iterate through a ref object

I have a small problem,
I get my ref object from that method
const dataAnimals = ref([])
function getDataAnimals() {
axios.get('/json/data_animal.json').then((response) => {
dataAnimals.value = response.data
})
}
getDataAnimals()
And i want to use another method using that ref object :
function countAnimal(type) {
dataAnimals.forEach((item) => {
if (animal.animal == type) {
total_hen += dataMint.value[animal.template_id]
}
return total_hen
})
}
const totalHen = countAnimal('hen')
But i can't iterate through :
dataAnimals.value.forEach((item) => {
Is there anyway to make that work ?
Thank you :)
As the response is an object and not an array, you cannot iterate over it with forEach, you need to use Object.entries()
function countAnimal(type) {
let total = 0;
for (const [key, item] of Object.entries(dataAnimals)) {
if (item.animal === type) {
total++;
}
}
return total;
}
const totalHen = countAnimal('hen');
And I would use a reactive object:
const dataAnimals = ref(null);
function getDataAnimals() {
axios.get('/json/data_animal.json').then((response) => {
dataAnimals.value = response.data
});
}
getDataAnimals()
Of course if you want that count to be reactive as well you'd need to use a computed property.

How do I get the IDs from firestore into the object arrays?

working on a React/Firestore app, trying to get the Id-s back into the objects array.
Here is the code:
function getEm() {
setLoading(true);
ref.onSnapshot((querySnapshot) => {
const items = [];
const ids = [];
querySnapshot.forEach((doc) => {
items.push(doc.data());
ids.push(doc.id);
});
//unzipped
setItems(items);
setIds(ids);
console.log(ids);
console.log(items);
//zipped
const item = _.zipObject([(ids = [])], [(items = [])]);
setItems(item);
setLoading(false);
});
}
Any idea on what is wrong with the '_zipObject' line?
You could just add the id to the data object as soon as you get it from the query snapshot:
querySnapshot.forEach((doc) => {
const newItem = {
...doc.data(),
id: doc.id
}
items.push(newItem);
});
This would give you an array of object with all the data from the object + the id

Modifying an array of objects with uuid keys

I've got add
I've got delete
now I need modify
add just adds to the pile haphazardly
delete is able to do it's work with surgical precision because it uses key to find it's culprit :
addInput = (name) => {
const newInputs = this.props.parameters;
newInputs.push({
name,
key: uuid(),
value: { input: '' },
icon: { inputIcon: 0 },
});
this.setState({
newInput: newInputs,
});
this.props.exportParameter(newInputs);
};
removeInput = (key) => {
const newInputs = this.props.parameters.filter(x => x.key !== key);
this.setState({
newInput: newInputs,
});
this.props.exportParameter(newInputs);
};
how do I modify (for example set the value back to '' without deleting and recreating the item) ?
modifyInput = (key) => {
?????
};
You can use Array.prototype.find()
modifyInput = (key) => {
const match = this.props.parameters.find(x => x.key === key);
// do stuff with matched object
};
You can map through the parameters and then modify when you find a match:
modifyInput = (key) => {
const newInputs = this.props.parameters.map(x => {
if (x.key === key) {
x.modification = true;
}
return x;
});
this.setState({
newInput: newInputs,
});
this.props.exportParameter(newInputs);
};
var empMap= {};
//initialize empMap with key as Employee ID and value as Employee attributes:
//Now when salary updated on UI from 100 - 300 you can update other fields
var e=empMap[id];
if(e){
e.Salary=newSalary;
e.YearlySalary = newSalary*12;
e.Deductions = e.YearlySalary*0.2;
empMap[id]=e;
}

Update elements of array of object when one element is changed [duplicate]

I've got add
I've got delete
now I need modify
add just adds to the pile haphazardly
delete is able to do it's work with surgical precision because it uses key to find it's culprit :
addInput = (name) => {
const newInputs = this.props.parameters;
newInputs.push({
name,
key: uuid(),
value: { input: '' },
icon: { inputIcon: 0 },
});
this.setState({
newInput: newInputs,
});
this.props.exportParameter(newInputs);
};
removeInput = (key) => {
const newInputs = this.props.parameters.filter(x => x.key !== key);
this.setState({
newInput: newInputs,
});
this.props.exportParameter(newInputs);
};
how do I modify (for example set the value back to '' without deleting and recreating the item) ?
modifyInput = (key) => {
?????
};
You can use Array.prototype.find()
modifyInput = (key) => {
const match = this.props.parameters.find(x => x.key === key);
// do stuff with matched object
};
You can map through the parameters and then modify when you find a match:
modifyInput = (key) => {
const newInputs = this.props.parameters.map(x => {
if (x.key === key) {
x.modification = true;
}
return x;
});
this.setState({
newInput: newInputs,
});
this.props.exportParameter(newInputs);
};
var empMap= {};
//initialize empMap with key as Employee ID and value as Employee attributes:
//Now when salary updated on UI from 100 - 300 you can update other fields
var e=empMap[id];
if(e){
e.Salary=newSalary;
e.YearlySalary = newSalary*12;
e.Deductions = e.YearlySalary*0.2;
empMap[id]=e;
}

Categories

Resources