0

I have an object which contains data from a WordPress API endpoint. All I want from it is the user's name. But to do that I have to iterate through the following hierarchy:

array [
    object {
        object {
            "name": foo
        }
    }
]

I tried variations on this but it's not returning what I need.

const userList = Object.values(this.state.userList[0]).map(value => {
    const newUserList = Object.values(value).map(value => {
        return value[name];
    });
    return newUserList;
});

What's the proper way to navigate an object tree like that?

j08691
  • 204,283
  • 31
  • 260
  • 272
Bryan White
  • 334
  • 1
  • 13
  • `value[name]` should be `value.name` – Barmar Oct 11 '19 at 15:31
  • 1
    Are you sure you need to loop through the object values? Can't you just access a the specific property that contains the object with the name? – Barmar Oct 11 '19 at 15:33
  • `array.map(o=>o.propname.name)` I don't see any problem? – apple apple Oct 11 '19 at 15:33
  • @Barmar is right: if you always want to have the first item of your array, then, use `[0]` and then reach your target value directly, no need to make loops. As is, your input data is quite blurry: please add real data structure and expected output, it'll be simpler for everyone to answer your question. – sjahan Oct 11 '19 at 15:35
  • @sjahan Actually, my comment was related to the `Object.values().map()` loop for the second level. – Barmar Oct 11 '19 at 15:36
  • @Barmar I think it is the same problem with the first level: you start with a collection: either you want a value for each element or just for the first one (`[0]`). Then, if it is only nested object, let's just reach the data: if the structure is fine and not random, there is no need to loop on that. So no `Object.values().map()`. But maybe we don't understand the real structure of the data right now. – sjahan Oct 11 '19 at 15:38

0 Answers0