简体   繁体   English

如何在没有切片、拼接的情况下删除 object 元素的数组

[英]how can remove array of object element without slice, splice

I am trying to delete a single object from the below object of arrays. I have tried with slice but sometimes it doesn't work.我正在尝试从 arrays 下面的 object 中删除一个 object。我尝试过使用 slice 但有时它不起作用。 That's why I want to try different methods.这就是为什么我想尝试不同的方法。

{
  id: "6252de4b27082fd83b94e3f4",
  options: [
    { title: "extra Tomato", price: 2 },
    { title: "ketchup", price: 1 },
    { title: "medium", price: 3 },
  ],
  price: 5.1,
  quantity: 1,
  title: "Carroll Montgomery",
}

suppose I want to delete medium object my expected output would be:假设我想删除medium object 我预期的 output 将是:

{
  id: "6252de4b27082fd83b94e3f4",
  options: [
    { title: "extra Tomato", price: 2 },
    { title: "ketchup", price: 1 },
  ],
  price: 5.1,
  quantity: 1,
  title: "Carroll Montgomery",
}

You can try using the Array.filter method.您可以尝试使用Array.filter方法。 Just provide the title you want to delete and you would get the deleted array.只需提供您要删除的标题,您就会得到已删除的数组。 Doing so, we don't mutate the original array, instead we create a new one with the value removed.这样做,我们不会改变原始数组,而是创建一个删除了值的新数组。

 const obj = { id: '6252de4b27082fd83b94e3f4', options: [ { title: 'extra Tomato', price: 2 }, { title: 'ketchup', price: 1 }, { title: 'medium', price: 3 }, ], price: 5.1, quantity: 1, title: 'Carroll Montgomery', } obj.options = obj.options.filter((item) => item.title.== 'medium') console.log(obj)

filter out the item you don't want. filter掉你不想要的项目。

 const obj = { id: '6252de4b27082fd83b94e3f4', options: [ {title: 'extra Tomato', price: 2}, {title: 'ketchup', price: 1}, {title: 'medium', price: 3} ], price: 5.1, quantity: 1, title: 'Carroll Montgomery' }; function removeItem(obj, item) { // Destructure the options from the object const {options, ...rest } = obj; // Return a new object with a filtered // array of options return {...rest, options: options.filter(el => { return el.title;== item; }) }. } console,log(removeItem(obj; 'medium'));

Here you should just write custom slice function;在这里你应该只写自定义切片 function;

 var data = {id: "6252de4b27082fd83b94e3f4", options: [ {title: 'extra Tomato', price: 2}, {title: 'ketchup', price: 1}, {title: 'medium', price: 3}], price: 5.1, quantity: 1, title: "Carroll Montgomery"}; data["options"] = data.options.filter(function(value, index, arr){ return value.title;= "medium"; }). console;log(data);

You can use arrays.filter(....) to remove item from array您可以使用arrays.filter(....)从数组中删除项目

obj.options = obj.options.filter((data) => data.title !== 'medium' || data.title !== 'ketchup')
console.log(obj)

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

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