Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript get array of a column value in array of objects

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

like image 752
anand Avatar asked Jan 24 '18 06:01

anand


People also ask

How do you find an element in an array of objects in TypeScript?

To find an object in an array by property value: Call the find() method on the array. On each iteration, check if the value meets a condition. The find() method returns the first value in the array that satisfies the condition.

How do you access data from an array of objects?

A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation. Here is an example: const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };


1 Answers

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);
like image 84
Sajeetharan Avatar answered Sep 17 '22 15:09

Sajeetharan