我必须从一组对象中获取数组。
数据
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)
预期的O / P
var data = [1,2,3,4]
我的代码没有返回预期的结果。提前致谢
答案 0 :(得分:6)
过滤器仅采用匹配值,您需要使用.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);
&#13;
答案 1 :(得分:1)
您需要使用地图
var data = result1.map(x => x.id)