-8

I am new to Javascript and jQuery. I am trying to create something like this (object) below and read the keys and retrieve the values.

var members = {unit:1,name: ["AA", "AB"],userid:["0001","0002"],
              {unit:2,name: ["BA", "BB"],userid:["0011","0012"]};

if 'Unit' == 1 then display name array.

Basically I want loop through the object and retrieve the value.

halfer
  • 19,824
  • 17
  • 99
  • 186
Charix
  • 29
  • 3
  • 1
    The object that you have given is invalid. It looks like, It has to be wrapped inside an array. – Rajaprabhu Aravindasamy Jun 02 '17 at 10:41
  • you have multiple properties with same name in a single object (?) you have one missing closing `}`.. do you mean an array of objects? [edit] your question please. – Suraj Rao Jun 02 '17 at 10:43
  • structure was not proper. your object should be, [{},{}] but currently its like {{}. rewrite it – Mohideen bin Mohammed Jun 02 '17 at 10:45
  • This question has been heavily downvoted, and it is worth taking a moment to understand why. Your title ("I want a solution in JavaScript please") seems to be a demand for free work rather than a statement of the problem. I have trimmed similar fluff material from the body as well. It also isn't clear, and there is no attempt at a solution. Did you try something before asking? That is really important here. – halfer Jun 02 '17 at 11:39
  • Possible duplicate of [JavaScript: filter() for Objects](https://stackoverflow.com/questions/5072136/javascript-filter-for-objects) – Francis.Beauchamp Jun 02 '17 at 13:35

2 Answers2

4

I think you member should be like this

var members = [{unit:1,name: ["AA", "AB"],userid:["0001","0002"]},
                  {unit:2,name: ["BA", "BB"],userid:["0011","0012"]}];

var members = [{unit:1,name: ["AA", "AB"],userid:["0001","0002"]},
              {unit:2,name: ["BA", "BB"],userid:["0011","0012"]}];
              
        members.forEach(function(v,i){
        
            if(v.unit==1)
            {
            
              console.log(v.name);
            }
        
        });
JYoThI
  • 11,977
  • 1
  • 11
  • 26
1

I guess this is want you wanted, an object within an object. Where 'unit' is the key for retrieving the objects within the object.

var members = {
    1: {
        name: ["test","test"],
        userid: ["0001","0002"]},
    2: {
        name: ["test2", "test2"],
        userid: ["0011", "0012"]}
};

console.log(members[1]);
Ecstabis
  • 434
  • 3
  • 16
  • 1
    Hi Hedylogos. I wanted something similar to your reply and I found the answer. Thank you very much – Charix Oct 12 '17 at 12:56
  • var members = { member:[ {"unit" : 4,"unit_name":"Ma","names":['-Select your name-','Mattias','Johan','Cecilia','Tuomas','Charika'],"codes":['0','199930','440720','237720','111111','111112']}, {"unit" : 5,"unit_name":"CM","names":['-Select your name-','Lena','Mariat','Annika'], "codes":['0','346710','297380']} ]} – Charix Oct 12 '17 at 13:00