删除多个JSON对象的键/值对

时间:2017-05-26 08:27:05

标签: javascript arrays json

我有一个包含多个JSON对象的数组。我不需要文件中的所有键/值,所以我想删除例如所有“完成”键及其在所有这些JSON对象中的值。 我知道我可以使用delete运算符删除特定的键/值对,但在数组中留下undefined个洞。我不希望这样,因为我认为以后在使用数组时会引起问题。

我也尝试过拼接:

data.splice(data[i].Completed, data.length);

拼接错误了吗?

我想创建一个没有特定键/值的新文件。在我的方法中,我只是操纵现有文件而不创建新文件......我怎么能这样做?

var data = [
{
    "ID": 1,
    "Titel": "ui sketch",
    "Completed": "yes",
    "Prio": 3,
    "Importance": 2
  },
  {
    "ID": 2,
    "Titel": "coding",
    "Completed": "yes",
    "Prio": 4,
    "Importance": 4
  },
  {
    "ID": 5,
    "Titel": "meeting",
    "Completed": "no",
    "Prio": 3,
    "Importance": 2
  },
]

5 个答案:

答案 0 :(得分:2)

如果你需要删除所有带有'Completed'等于'yes'键的对象,你可以:

const newData = data.filter(el => el.Completed !== 'yes')

如果您需要删除所有密钥已完成,以防它们等于'是',您可以:

const newData = data.map(el => {
  if (el.Completed === 'yes') delete el.Completed
  return el;
})

在大多数情况下,对象使用delete,对于Arrays,使用splice。

答案 1 :(得分:0)

我从您的问题中了解到,您要删除Completed数组中对象的所有data属性。

在这种情况下,您可以使用Array.prototype.map()创建一个包含所需属性的对象的新数组:



var data = [{"ID": 1,"Titel": "ui sketch","Completed": "yes","Prio": 3,"Importance": 2},{"ID": 2,"Titel": "coding","Completed": "yes","Prio": 4,"Importance": 4},{"ID": 5,"Titel": "meeting","Completed": "no","Prio": 3,"Importance": 2}],
    result = data.map(elem => {
      return {
        ID: elem.ID,
        Titel: elem.Titel,
        Prio: elem.Prio,
        Importance: elem.Importance
      };
    });

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 2 :(得分:0)

您可以使用Array.prototype.filter()方法:documentation on MDN

这是它的样子:

var data = [
{
    "ID": 1,
    "Titel": "ui sketch",
    "Completed": "yes",
    "Prio": 3,
    "Importance": 2
  },
  {
    "ID": 2,
    "Titel": "coding",
    "Completed": "yes",
    "Prio": 4,
    "Importance": 4
  },
  {
    "ID": 5,
    "Titel": "meeting",
    "Completed": "no",
    "Prio": 3,
    "Importance": 2
  },
]

// New array from former one.
var undone = data.filter(obj => obj["Completed"] != "yes");

// Skim data from completed elements
data = data.filter(obj => obj["Completed"] != "yes");

答案 3 :(得分:0)

var data = [
{
    "ID": 1,
    "Titel": "ui sketch",
    "Completed": "yes",
    "Prio": 3,
    "Importance": 2
  },
  {
    "ID": 2,
    "Titel": "coding",
    "Completed": "yes",
    "Prio": 4,
    "Importance": 4
  },
  {
    "ID": 5,
    "Titel": "meeting",
    "Completed": "no",
    "Prio": 3,
    "Importance": 2
  },
]

var i =data.length-1;
for(i ; i>= 0;i--){
    if(data[i].Completed == "yes"){
        data.splice( i, 1 );
    }
}
alert(data[0].Titel);

在这里你有它,搜索完成==“是”,如果是这样,拼接它,你最终得到一个带有1个元素的数组:)希望它有所帮助

答案 4 :(得分:0)

试试这个:

system(paste0("source activate ncl_stable;cd /home;ncl_convert2nc myfile.grb2"))