我正在尝试从数组中提取数据,但是我只想提取id字段,而不是name字段。使用Json Stringify,我可以将结果记录在控制台中,下面是代码和结果:
控制台日志:
console.log(JSON.stringify(this.selectedCustomers));
结果:
[{"id":1,"name":"John"},{"id":2,"name":"Jane"}]
期望的结果应该是:[1,2]
我尝试以下想法,它将过滤结果:
console.log(JSON.stringify(this.selectedCustomers.id));
但是我收到以下错误消息:“类型'any []'上不存在属性'id']
如何删除名称字段并仅提取ID?如果有人可以告诉我我所缺少的内容或仅如何获取ID,将不胜感激!谢谢!
您需要使用map
方法和destructuring。
let result = this.selectedCustomers.map(({id}) => id);
简短示例:
let arr = [{"id":1,"name":"John"},{"id":2,"name":"Jane"}]
console.log(arr.map(({id}) => id));