Typescript get array of a column value in array of objects

19,405

Solution 1

Filter will take only the matching values, You need to use .map

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

DEMO

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);

Solution 2

You need to use map

var data = result1.map(x => x.id)
Share:
19,405
anand
Author by

anand

I have skills in asp.net mvc, html, css, sql, javascript, jquery and codigniter.

Updated on July 04, 2022

Comments

  • anand
    anand almost 2 years

    i have to get array from an array of objects.

    Data

    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'}
    

    My Code

    var data = result1.filter(x => x.id)
    

    Expected O/P

    var data = [1,2,3,4]
    

    my code is not returning the expected result. Thanks in advance