Typescript获取对象数组中某一列的值的数组

7
我需要从一个对象数组中获取数组。
数据:无。
var result1 = [
    {id:1, name:'Sandra', type:'user', username:'sandra'},
    {id:2, name:'John', type:'admin', username:'johnny2'},
    {id:3, name:'Peter', type:'user', username:'pete'},
    {id:4, name:'Bobby', type:'user', username:'be_bob'}

我的代码
var data = result1.filter(x => x.id)

预期输出
var data = [1,2,3,4]

我的代码没有返回预期的结果。提前致谢。

可能是Typescript按数组过滤对象数组的重复问题。 - Aravind
2个回答

18

筛选器将只获取匹配的值,您需要使用 .map

var data = result1.map(x => x.id);

演示

var result1 = [
    {id:1, name:'Sandra', type:'user', username:'sandra'},
    {id:2, name:'John', type:'admin', username:'johnny2'},
    {id:3, name:'Peter', type:'user', username:'pete'},
    {id:4, name:'Bobby', type:'user', username:'be_bob'}];
    
 
var data = result1.map(t=>t.id);
console.log(data);


3
您需要使用map。
var data = result1.map(x => x.id)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接