【问题标题】:Remove JSON objects not containing a specific field删除不包含特定字段的 JSON 对象
【发布时间】:2020-06-10 21:48:40
【问题描述】:

我想使用 node/js 从以下内容中删除每个不包含名称字段的对象:

[{
    "20": "Start Date:",
    "28": "15/06/2020",
},
{
    "name": "Jun/Jul 2020",
    "Monday 15th June": "Mon",

},
{
    "Monday 15th June": 15,
    "Tuesday 16th June": 16
},
{
    "name": "Charlie Sheen"
},
{
    "name": "Ray Liotta",
    "Thursday 18th June": "08:00-18:00:T5&6"
},
{
    "Thursday 18th June": "Theatres 5&6"
},
{
    "name": "Neil, Whatever"
},
{
    "3": "Theatres 1&2"
},
{
    "name": "Joe,  Bloggs",
    "Monday 15th June": "08:00-17:00:T1&2"
}]

我想要的最终输出是:

[
{
    "name": "Jun/Jul 2020",
    "Monday 15th June": "Mon",

},
{
    "name": "Charlie Sheen"
},
{
    "name": "Ray Liotta",
    "Thursday 18th June": "08:00-18:00:T5&6"
},
{
    "name": "Neil, Whatever"
},
{
    "name": "Joe,  Bloggs",
    "Monday 15th June": "08:00-17:00:T1&2"
}]

非常感谢!

【问题讨论】:

  • 我不知道这个结构是什么,但它很乱。你目前有什么尝试?
  • 到目前为止你有什么尝试?
  • 谢谢大家,太棒了 - 工作愉快,感激不尽!
  • 您应该接受其中一个答案。它给写答案的人打分。

标签: javascript node.js arrays json


【解决方案1】:

您可以使用Array#filter。请注意,filter 创建了一个包含过滤元素的新数组,因此如果要更改原始数组,则需要将结果分配给包含该数组的变量。

arr = arr.filter(obj=>'name' in obj);

const arr = [{
    "20": "Start Date:",
    "28": "15/06/2020",
},
{
    "name": "Jun/Jul 2020",
    "Monday 15th June": "Mon",

},
{
    "Monday 15th June": 15,
    "Tuesday 16th June": 16
},
{
    "name": "Charlie Sheen"
},
{
    "name": "Ray Liotta",
    "Thursday 18th June": "08:00-18:00:T5&6"
},
{
    "Thursday 18th June": "Theatres 5&6"
},
{
    "name": "Neil, Whatever"
},
{
    "3": "Theatres 1&2"
},
{
    "name": "Joe,  Bloggs",
    "Monday 15th June": "08:00-17:00:T1&2"
}];
const res = arr.filter(obj=>"name" in obj);
console.log(res);

【讨论】:

    【解决方案2】:

    const data = 
    [{ "20": "Start Date:", "28": "15/06/2020", }, { "name": "Jun/Jul 2020", "Monday 15th June": "Mon",
    
    },
    {
        "Monday 15th June": 15,
        "Tuesday 16th June": 16
    },
    {
        "name": "Charlie Sheen"
    },
    {
        "name": "Ray Liotta",
        "Thursday 18th June": "08:00-18:00:T5&6"
    },
    {
        "Thursday 18th June": "Theatres 5&6"
    },
    {
        "name": "Neil, Whatever"
    },
    {
        "3": "Theatres 1&2"
    },
    {
        "name": "Joe,  Bloggs",
        "Monday 15th June": "08:00-17:00:T1&2"
    }]
    const filteredData = data.filter(item => item.name)
    console.log(filteredData)

    【讨论】:

    • 我为什么不在几小时前问这个!?!谢谢你,完美!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-09
    • 2022-10-13
    • 2012-03-21
    • 2012-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多