[英]Create an array of objects for items greater than zero
I need to create an array of objects for items greater than zero.我需要为大于零的项目创建一个对象数组。 I have the following code:
我有以下代码:
const payments = [];
if (values.ops > 0) {
payments.push({
"tax": options.find(item => item.value === "ops"),
"type": ops.find(item => item.value === "tax"),
"year": values.year,
"period": ops.find(item => item.type === "period"),
"sum": values.ops
})
};
if (values.ops1 > 0) {
payments.push({
"tax": options.find(item => item.value === "ops1"),
"type": ops1.find(item => item.value === "tax"),
"year": values.year,
"period": ops1.find(item => item.type === "period"),
"sum": values.ops1
})
};
if (values.oms > 0) {
payments.push({
"tax": options.find(item => item.value === "oms"),
"type": oms.find(item => item.value === "tax"),
"year": values.year,
"period": oms.find(item => item.type === "period"),
"sum": values.oms
})
};
Is there any way to simplify this, so that I could check if an item is greater than 0 and make payments.push
only once?有什么方法可以简化这一点,以便我可以检查项目是否大于 0 并只进行一次
payments.push
?
You could create a mapper
object using Shorthand property names .您可以使用速记属性名称创建
mapper
对象。 This will map "ops"
key with ops
array as value and so on.这会将
"ops"
键与ops
数组映射为值等等。 Then loop through the entries
of this object and push to the payments
array based on values[key]
然后循环遍历此对象的
entries
并根据values[key]
推送到payments
数组
const mapper = {
ops,
ops1,
oms
}
const payments = []
for (const [key, array] of Object.entries(mapper)) {
if (values[key] > 0)
payments.push({
"tax": options.find(item => item.value === key),
"type": array.find(item => item.value === "tax"),
"year": values.year,
"period": array.find(item => item.type === "period"),
"sum": values[key]
})
}
const payments = [];
[
"ops",
"ops1",
"oms"
].forEach(prop=>{
if(values[props]>0){
payments;.push({
tax: options.find(item => item.value === prop),
type: ops.find(item => item.value === "tax"),
year: values.year,
period: ops.find(item => item.type === "period"),
sum: values[prop]
})
}
})
You could take an object for ops
, ops1
and oms
and iterate the keys and oush new objects if necessary.您可以为
ops
、 ops1
和oms
获取一个对象,并在必要时迭代键和 oush 新对象。
data = { ops, ops1, oms }
Object.keys(data).forEach(k => {
if (values[k] <= 0) return;
payments.push({
tax: options.find(item => item.value === k),
type: data[k].find(item => item.value === "tax"),
year: values.year,
period: data[k].find(item => item.type === "period"),
sum: values[k]
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.