根据键从数组中删除项目

我有 MAinArray


MainArray=[{

{First Name: "First Name"},

{Last Name: "Contact"},

{Last Name: "Contact"}

]

我想从这个数组中删除键值对,例如


if (key == 'First Name')

{

delete MainArray[key] /// this doesnt work

}

最终结果必须是


ResultArray=[{

    {Last Name: "Contact"},

    {Last Name: "Contact"}

    ]


茅侃侃
浏览 88回答 2
2回答

人到中年有点甜

您可以使用当前对象的filter内部和内部,Object.keys并检查它是否包含给定的过滤器:var MainArray=[ {'First Name': "First Name"}, {'Last Name': "Contact"}, {'Last Name': "Contact"} ];var result = MainArray.filter(item=>!Object.keys(item).includes('First Name'));var result2 = MainArray.filter(item=>!item['First Name']);console.log(result);console.log(result2);

扬帆大鱼

filter()方法也可用于根据给定条件删除项目,请参见以下示例:let data=[{"First Name": "First Name"},{"First Name": "First Name"},{"Last Name": "Contact"},{"Last Name": "Contact"}]const keyToRemove = "First Name"; //Key to removedata = data.filter(x => !x[keyToRemove]);console.log(data);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript