从json数据中删除特定的或选定的属性。我不想删除所有具有Category:null的键值对

时间:2019-05-31 06:45:15

标签: javascript json

这是我的json数据,我想从json中删除具有空值的类别。

我的意思是不删除RewriteEngine on RewriteCond %{QUERY_STRING} ^(.+)$ RewriteRule ^(\/)?$ /404.php? [L,R=404] ,而是删除"Category":"start"
我已经看到了一些有关此问题的答案,但它删除了我不想要的所有类别,包括"Category":null

"Category":"start"

2 个答案:

答案 0 :(得分:1)

请参见下面的代码。这将为您提供期望的输出。

const array = [{
  "category": "Start",
  "name": "Start",
  "key": 1,
  "lastname": "xyz"
}, {
  "category": null,
  "text": "Step",
  "key": 2,
  "lastname": "xyz"
}, {
  "category": null,
  "text": "Condition",
  "key": 3,
  "loc": "xyz"
}];

const list = array.map(item => {
  let object = item;
  [undefined, null].includes(object.category) && delete object.category;
  return object;
});

console.log(list);

答案 1 :(得分:1)

您可以使用map()并破坏函数的参数。

const arr = [{ "category": "Start", "name": "Start", "key": 1, "lastname": "xyz" }, { "category": null, "text": "Step", "key": 2, "lastname": "xyz" }, { "category": null, "text": "Condition", "key": 3, "loc": "xyz" } ]

const res = arr.map(({category,...rest}) => category === null ? {...rest} : {category,...rest})
console.log(res)