-1

I am trying to access a specific field inside the nested array. My code is like this:

var array1 = [];

const data =  { [userId]: [{
             id: id,
             name: fullName,
             email: userEmail },
            ],
          };

array1.push(data);

If I print this:

console.log("index 0: ", array1[0]);

It gives this result:

index 0:  {
  buMqSZpEaKZABffDGNs5jzVK36Y2: [
    {
      id: '65',
      name: 'nameTest',
      email: 'myexmail@gmail.com'
    }
  ]
}

However, I would like to know how I can access the information inside the userId, like userId.name and be able to find a specific userId. For example, in the array1 find userId "aePoUZpkUnlAOMNBGNs5ynMD36L1" and display its information as if I did like this activeSockets[0]. or indexOf(). Most of the times I have tried accessing the fields inside it says Cannot read property '' of undefined. Any help will appreciated

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
UAJ
  • 21
  • 4
  • 1
    So, before we go down this road, quick question. What is the purpose of the array? Since your object has the key of the userid, and you can have multiple key value pairs in an object, what is your intended usage of the array? – Taplar Jan 28 '20 at 23:24
  • So I can compare to check if the userid exists in the array, if exists only replace the id inside the userid – UAJ Jan 28 '20 at 23:28
  • That can be done with a simple object. `data[userId]` will return undefined or null if it does not exist. And if it does exist, `data[userId].id = ` works too – Taplar Jan 28 '20 at 23:29
  • I want to deal with array1[ ] because I push the data into it. The data[ ] will loose the old information. – UAJ Jan 28 '20 at 23:32
  • So you're planning on having an array, that contains objects which consist of a single key to a sub-object value? – Taplar Jan 28 '20 at 23:32
  • I did not get what you mean but, the structure is this: { buMqSZpEaKZABffDGNs5jzVK36Y2: [ { id: '65', name: 'nameTest', email: 'myexmail@gmail.com' } ] } – UAJ Jan 28 '20 at 23:33
  • And your wanting to put that in an array. So it's actually something like, `[ { buMqSZpEaKZABffDGNs5jzVK36Y2: [ { id: '65', name: 'nameTest', email: 'myexmail@gmail.com' } ] }, { buMqSZpEaKZABffDGNs5jzVK3333: [ { id: '78', name: 'nameTest2', email: 'blah@gmail.com' } ] } ]` ? – Taplar Jan 28 '20 at 23:35
  • Yes. I am able to put in the array1. But I have problem accessing the data inside. – UAJ Jan 28 '20 at 23:39
  • 1
    Right, so what my comments are saying is that outer most array is unnecessary, and is going to create problems that you have to solve. So I'm suggesting instead of solving the problem, don't create it in the first place. – Taplar Jan 28 '20 at 23:40
  • And how am I supposed to organize the information so that every user's fields are accessed through the userId? – UAJ Jan 28 '20 at 23:42
  • Your `userId` are the keys of the single object. [Your version](https://jsonblob.com/3d6fe6b9-4228-11ea-9498-fb21253edeb7). [My proposal](https://jsonblob.com/60fd27d4-4228-11ea-9498-897ab40e8177) My version will not require you to perform a filter/find on the object every time you need to access a user by their userid – Taplar Jan 28 '20 at 23:44
  • That is how I did, if you check the description. My problem is to access a field, let's say the name or email inside. – UAJ Jan 28 '20 at 23:48
  • That's not how you did it. Your OP has the data being put in an `array1`, and then later you use `array1[0]` to access it. If you have multiple users, you will have to perform a find to get it. If you don't use an array, and use just the object, you don't have to do the find. – Taplar Jan 28 '20 at 23:49
  • 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) – Taplar Jan 28 '20 at 23:52
  • For what data you have provided and the for the objective you described, your use (*misuse?*) of array and object data structures are over complicated. You should have only one object for each user then push them into one array. An array with only one user object is absurd especially if that array is then stuffed into an object that is then crammed into another array. – zer00ne Jan 29 '20 at 00:06
  • Taplar I am reading ...the link you shared to understand better – UAJ Jan 29 '20 at 00:16
  • 1
    Zero00ne I did not notice I was having array for each user, I corrected by removing extra [ ] – UAJ Jan 29 '20 at 00:17

1 Answers1

0

You can find the object of the userid in the array.

var array1 = [];

var data =  { ['ABC123']: [{
     id: 1,
     name: 'john',
     email: 'john.doe@nomail.com'
      },
    ],
  };

array1.push(data);

let userId = 'ABC123';

let userObj = array1.find((x)=> x[userId] !== undefined);

if(userObj) {  // did the find return an object?
    let userData = userObj[userId][0];
    console.log(`name: ${userData.name}`);
    console.log(userData);
}
else {
    console.log(`user ${userId} not found.`);
}

By the way, it's not so common that a value would be used as a property name.
More often, such key is just a value of an objects property.

Which also makes the find or filter more straightforward.

For example:

var array1 = [];

array1.push({
         userid : 'ABC123',
         id: 1,
         name: 'john',
         email: 'john.doe@nomail.com'
      });

let userId = 'ABC123';
let userData = array1.find((x)=> x.userid === userId);

if(userData) {  // did the find return an object?
    console.log(`name: ${userData.name}`);
    console.log(userData);
}
else {
    console.log(`user ${userId} not found.`);
}
LukStorms
  • 28,916
  • 5
  • 31
  • 45
  • Thanks, but what if I want to get only the name field inside the ABC123? – UAJ Jan 28 '20 at 23:51
  • I get undefined for the name. console.log(userData.name); – UAJ Jan 29 '20 at 00:00
  • The name is in an object that's in array. See update. – LukStorms Jan 29 '20 at 00:13
  • I am not sure why I keep getting the Cannot read property 'name' of undefined with console.log('name: ', userData[0].name); – UAJ Jan 29 '20 at 00:20
  • Did you notice that `[userId]` was used at the end of the find ? – LukStorms Jan 29 '20 at 00:23
  • That is what I was missing. Thanks. – UAJ Jan 29 '20 at 00:25
  • ['ABC123']: [{ }] isn't it creating another array, I mean for each userId? – UAJ Jan 29 '20 at 00:31
  • I can't answer that. I don't know the data nor it's purpose. But I do find it suspicious that the user data objects are in an array. – LukStorms Jan 29 '20 at 00:34
  • I corrected by removing [ ] to ['ABC123']: { } and removing [0] from console.log('name: ', userData.name); the result is: { buMqSZpEaKZABffDGNs5jzVK36Y2: { id: '65', name: 'nameTest', email: 'myexmail@gmail.com' } } – UAJ Jan 29 '20 at 00:40
  • Ok. Good that you figured it out. Well, personally I would prefere a [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) object for key/value pairs. – LukStorms Jan 29 '20 at 01:37
  • @UAJ Anyway, Map isn't fully supported yet by IE anyway. But I added a sidenote to the answer. – LukStorms Jan 29 '20 at 11:38
  • thanks for the explanation. There is something I don't understand. For example, if(array1.find((x)=> x[userId] !== undefined)[userId]){}else{}. if it finds the id it does work, but if it doesn't find the id in the array it throws error Cannot read property 'xgyuFT145Tbgc' of undefined. Wasn't if supposed to execute 'else' and not throw error even if the 'else' is not there, pass. Even let userData = array1.find((x)=> x[userId] !== undefined)[userId]; if it does not find the id will give error. I wanted to check the userid, if the userid is in the array replace 'id' with a new id. – UAJ Jan 29 '20 at 15:17
  • Well, that's true. Can't get a property from undefined. I've updated the answer with a check. – LukStorms Jan 29 '20 at 15:47
  • It checks, but does not return an object.....Cannot read property 'name' of undefined – UAJ Jan 29 '20 at 16:52
  • Hmm, how about you log what's returned from the find. And see what you're getting from it. When I tested the current code it'll go to the `else` when the userId isn't in the array and nothing is found. In my code I still used the `[0]` to get the first value of that array with the object that has id. But if your object doesn't have such array that `[0]` ain't needed. – LukStorms Jan 29 '20 at 16:58
  • Now it does return an object. Thanks – UAJ Jan 29 '20 at 17:05