-1

I want to get the value from array. I am using javascript. My array is

[{"username1" : "123456"},{"username2" : "121"}]

I want to get the value of username1. I want print 123456 using username1. How it possible? Please help me? My code is shown below.

var categories = [];

  categories.push({"username1" : "123456"});

for (var i = 0; i < categories.length; i++) {
for (var categoryid in categories[i]) {
    var category = categories[i][categoryid];
    // log progress to the console
    console.log(categoryid + " : " + category);

}

It shows print all values and object in array.

Fazil
  • 109
  • 1
  • 2
  • 8
  • 2
    Possible duplicate of [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Teemu Apr 18 '17 at 07:59
  • @Teemu I am trying to understand why it is a dupe of that. OP know how to access them :) – Suresh Atta Apr 18 '17 at 08:00
  • @ANS Do they..? The answer in that question answers all the accessing problems, including iterations of known/unknown length etc ... – Teemu Apr 18 '17 at 08:03

1 Answers1

1

That is not an "associative array" - it is a single dimensional array of objects.

An associative array would look like

var myArr = {"username1" : "123456","username2" : "121"};

And you would et your value using

var result = myArr.username1;
//or
var result = myArr["username1"];

To access your value using the example you posted you would use

var result = myArr.filter(x => x.username1)[0].username1;
Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • when using var result = myArr.username1; or var result = myArr.username1;. It shows undefined. – Fazil Apr 18 '17 at 08:10
  • This is my array [{"username1" : "123456"},{"username2" : "121"}]. Or how to push value to this array {"username1" : "123456,"username2" : "121"}. – Fazil Apr 18 '17 at 09:21
  • @Fazil - once again, did you even read my answer? (Specifically: The last line of text and code). – Jamiec Apr 18 '17 at 09:24
  • When i using in socket io it shows. Cannot read property 'user' of undefined. my code is var result = categories.filter(x => x.user)[0].user;. why it shows error in socket io. – Fazil Apr 18 '17 at 10:17