简体   繁体   English

如何从数组中的 object 中删除属性?

[英]How can I remove a property from an object in an array?

I have an array in my Vue component that I'm trying to parse out in a method, but I don't want the ID in it at all.我的 Vue 组件中有一个数组,我试图在一个方法中解析它,但我根本不想要其中的 ID。 I want the array to be the same as it is currently but only show the option index, not the id.我希望数组与当前相同,但只显示选项索引,而不是 id。

Is there a way, within the method, that I can pop the ID index out of the array entirely?在该方法中,有没有一种方法可以将 ID 索引完全从数组中弹出?

 var vm = new Vue({ el: "#app", data: { options: [ {id:100, option:"1 - John Doe"}, {id:200, option:"2 - Jane Doe"} ] }, methods: { getNames(){ let names = this.options; console.log(names); } } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <button @click="getNames()">TEST</button> </div>

You can use map method:您可以使用map方法:

 var vm = new Vue({ el: "#app", data: { options: [ {id:100, option:"1 - John Doe"}, {id:200, option:"2 - Jane Doe"} ] }, methods: { getNames(){ let names = this.options.map(o => o.option); console.log(names); } } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <button @click="getNames()">TEST</button> </div>

You can loop through the array and create another array您可以遍历数组并创建另一个数组

 var vm = new Vue({ el: "#app", data: { options: [ {id:100, option:"1 - John Doe"}, {id:200, option:"2 - Jane Doe"} ] }, methods: { getNames(){ let names = this.options.map(option => { return { id: option.option } }); console.log(names); } } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <button @click="getNames()">TEST</button> </div>

This is a pure JavaScript task.这是一个纯粹的 JavaScript任务。 It is solvable independently from VueJS or any other framework.它可以独立于 VueJS 或任何其他框架来解决。

In general you can apply two approaches (either keep what is needed or remove what is obsolete):一般来说,您可以应用两种方法(保留需要的内容或删除过时的内容):

  1. map : to transform each source element to the new target format; map :将每个源元素转换为新的目标格式; returns a new array返回一个新数组
  2. forEach with delete : to remove the unwanted property from the original array forEachdelete :从原始数组中删除不需要的属性
let options: [
  {id:100, option:"1 - John Doe"},
  {id:200, option:"2 - Jane Doe"}
];

// to get a new (simple) array of strings
let strings = options.map(o => o.option);
console.log(strings);

// to get the same array with nested objects where property was removed
options.forEach(o => delete o.id);
console.log(options);

See also: Remove property for all objects in array另请参阅: 删除数组中所有对象的属性

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

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