简体   繁体   English

根据键而不是值从数组中删除对象?

[英]remove an object from array based on key not value?

I have an array of the object where I want to remove an object based on key?我有一个对象数组,我想根据键在其中删除一个对象? I tried with filter, omit in lodash but nothing worked.我尝试使用过滤器,在 lodash 中省略,但没有任何效果。 the description can be in any position描述可以在任何位置

Input输入

input = [{product: "abc", value: "123"},{name: "def", value: "234"},{description: ["abd123"]}]

Expected Output预期产出

output = [{product: "abc", value: "123"},{name: "def", value: "234"}]

const result = input.filter(el => el.key !== description)

You'd declare array this way:你可以这样声明数组:

const input = [{product: "abc", value: "123"},{name: "def", value:"234"},{description: ["abd123"]}];

and delete your object using some function as并使用某些功能删除您的对象

let output = input.filter(object => !object.hasOwnProperty("description"));

so that以便

output = [{product: "abc", value: "123"},{name: "def", value:"234"}];

 const input = [{product: "abc", value: "123"},{name: "def", value:"234"},{description: ["abd123"]}]; let output = input.filter(object => !object.hasOwnProperty("description")); output = [{product: "abc", value: "123"},{name: "def", value:"234"}]; console.log(output);

if you would like to remove any object has key use hasOwnProperty to check如果您想删除任何具有密钥的对象,请使用 hasOwnProperty 进行检查

let input = [{product: "abc", value: "123"},{name: "def", value: "234",description:0},{description: ["abd123"]}]


let output = input.filter(el=> !el.hasOwnProperty('description'))

你可以这样做:

input.filter(el=> !el.description)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM