如果名称和值对js中的值为空,则从数组中删除对象

时间:2018-10-08 14:54:44

标签: javascript arrays object

[{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为空,我想从数组中删除名称和值对。

我尝试了这种解决方案:但这没用

formData.map((i) => {
  (i.value == "") ? delete i: "";
});

我知道这是一个简单的问题,但是我找不到任何相关的示例来解决此问题。我发现的所有示例和解决方案都是针对此类对象的

let obj = {"firstname": "XYZ", "lastname": "ABC"}

两个对象之间有什么区别?

3 个答案:

答案 0 :(得分:7)

您可以使用Array.prototype.filter并根据布尔值来返回条目,因为空字符串是伪造的,因此value是否存在。

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

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

答案 1 :(得分:1)

对于您的问题标题,我认为“删除”是指使数组变异(更改其实际内容)。如果是这样,您可以这样做:

const copy = arr.slice(); // copy of array for iterating without getting the index (`i`) wrong
let count = 0;
copy.forEach((val, i) => { if (!val.value) arr.splice(i - count++, 1); });
                      // maybe `val.value != ""` instead of `!val.value` ?

演示:

var arr = [{name: "mode",value: "1"}, {name: "group", value: ""}, {name: "from_date",value: ""}, {name: "to_date", value: "2018-10-16"}, {name: "action",value:"ac_filter_transactions"}];

const copy = arr.slice();
let count = 0;
copy.forEach((val, i) => { if (!val.value) arr.splice(i - count++, 1); });
console.log(arr); // print original array, not a copy


或者,如果您不想更改数组(不更改其实际内容),则可以像这样制作(过滤的)副本:

const copy = arr.filter(val => !!val.value)

演示:

var arr = [{name: "mode",value: "1"}, {name: "group", value: ""}, {name: "from_date",value: ""}, {name: "to_date", value: "2018-10-16"}, {name: "action",value:"ac_filter_transactions"}];

console.log(arr.filter(val => !!val.value)); // print a copy, not the original array

答案 2 :(得分:0)

Array.map将在新数组中返回相同数量的项目。因此,您需要改为使用Array.reduce。

formData.reduce((result, item) => {
  if (item.value) {
    result.push(item);
  }

  return result;
}, []);