0

I have an object and want to get userName.

const example = [
  {
    id: 793,
    name: 'John',
    weight: '66',
    data: [
      {
        id: 793,
        userName: 'John Ferny',
      },
    ],
  },
];

I'm not sure that example.data.filter((item) => item === item.userName is correct

Festina
  • 327
  • 3
  • 17
  • 1
    Does this answer your question? [How can I access and process nested objects, arrays or JSON?](https://stackoverflow.com/questions/11922383/how-can-i-access-and-process-nested-objects-arrays-or-json) – aerial Nov 22 '21 at 06:39
  • `example[0].data[0].userName`. – Andy Nov 22 '21 at 06:40
  • The code can only be correct if you fix the syntax errors, i.e. the missing parentheses. Whether or not that _fixed_ code is _correct_ depends on a few things you didn’t tell us about, e.g. whether you’ve tried it and it provides the desired result, or what you need from `example` in general, if the object changes. See the linked post and use the available static and instance methods of [`Object`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#Static_methods) and [`Array`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods). – Sebastian Simon Nov 22 '21 at 06:43

1 Answers1

3

Directly:

const userName = example[0].data[0].userName;

If more than one userName:

const userNames = example.flatMap(({data}) => data.map(({userName})=> userName));

To FIND the first item with userName === "John Ferny"

const item = example.filter(item => item.data.find(({userName}) => userName === user))

const example = [{ id: 793, name: 'John', weight: '66', data: [ { id: 793, userName: 'John Ferny',}, ], },{ id: 794, name: 'Fred', weight: '66', data: [ { id: 794, userName: 'Fred Ferny',}, ], },];

// directly

console.log(example[0].data[0].userName)

// If more than one:

const userNames = example.flatMap(({data}) => data.map(({userName})=> userName))

console.log(userNames)

// To find an object with userName === something

const user = "John Ferny"
const item = example.filter(item => item.data.find(({userName}) => userName === user))
console.log(item)
mplungjan
  • 169,008
  • 28
  • 173
  • 236