问题描述
[{name: "mode", value: "1"},{name: "group", value: ""},{name: "from_date", value: ""},{name: "to_date", value: "2018-10-16"},{name: "action", value: "ac_filter_transactions"}
这是我的数组的样子.如果 value
为空,我想从数组中删除名称和值对.
This is how my array looks like. I want to remove the name and value pair from the array if the value
is empty.
我尝试了这种解决方案:但这没用
I tried this solution: but this didn't work
formData.map((i) => {
(i.value == "") ? delete i: "";
});
我知道这是一个简单的问题,但我找不到任何相关的示例来解决此问题.我发现的所有示例和解决方案都是针对此类对象的
I know this is a simple question but I couldn't find any relevant example to solve this problem. All examples and solutions I found was for this type of object
let obj = {"firstname": "XYZ", "lastname": "ABC"}
两个对象之间有什么区别?
What are the difference between both the objects?
推荐答案
您可以使用 Array.prototype.filter
,并根据布尔值(由于空字符串而存在 value
)返回条目是虚假的.
You can use Array.prototype.filter
and return entries based on a boolean of whether or not the value
exists since an empty string is falsy.
a.filter(o => (o.value));
let a = [{name: "mode", value: "1"},{name: "group", value: ""},{name: "from_date", value: ""},{name: "to_date", value: "2018-10-16"},{name: "action", value: "ac_filter_transactions"}];
let result = a.filter(o => (o.value));
console.log(result);
注意:如果您的任何 value
属性也都是虚假的,则它们也不会被选中.为了解决这个问题,您可以简单地使用以下代码重写它:(o.value!==")
Note: If the any of your value
properties are also falsy, they won't be picked up either. To get around this you could simply rewrite it using: (o.value !== "")
let a = [{name: "mode", value: "1"},{name: "group", value: ""},{name: "from_date", value: ""},{name: "to_date", value: "2018-10-16"},{name: "action", value: "ac_filter_transactions"}];
let result = a.filter(o => (o.value !== ""));
console.log(result);
这篇关于如果名称和值对js中的值为空,则从数组中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!