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
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.
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' }] };
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With