0

I have a sample data object below, and I want to get the expected output data.

I have research and end to these sites but I'm having difficutly to apply it. related-link1 related-link2

Someone knows how to do it in a shortest way as possible? thanks


My sample data:

[
    {
        id: 1,
        username: user_1,
        user: {
            name: 'Cuppelo'
        }
    },
    {
        id: 2,
        username: user_2,
        user: {
            name: 'John'
        }
    },
    {
        id: 3,
        username: user_3,
        user: {
            name: 'Jane'
        }
    }
]

Expected output: ['Cuppelo', 'John', 'Jane']

schutte
  • 1,949
  • 7
  • 25
  • 45

2 Answers2

1

Assuming the sample data array is saved to variable users, the following would give you a new array that matches your expected output:

users.map(ea => ea.user.name);
Dan K.
  • 102
  • 1
  • 10
1

Use Array.map

const user_1 = 'something';
const user_2 = 'something';
const user_3 = 'something';

const arr_1 = [
    {
        id: 1,
        username: user_1,
        user: {
            name: 'Cuppelo'
        }
    },
    {
        id: 2,
        username: user_2,
        user: {
            name: 'John'
        }
    },
    {
        id: 3,
        username: user_3,
        user: {
            name: 'Jane'
        }
    }
];

const arr_2 = arr_1.map(obj => obj.user.name);

console.log(arr_2);
code_monk
  • 9,451
  • 2
  • 42
  • 41