简体   繁体   中英

seperate out an array of objects inside an object (Javascript)

I have a data object. If i do console.log(data), here is the output.

Object {Info: Array[3]}
  > Info: Array[3]
     >[0]: Object
           name: 'Alex'
           sex: 'Male'
           new_joinee: 0
     >[1]: Object
           name: 'Anna'
           sex: 'female'
           new_joinee: 1
     >[2]: Object
           name: 'lester'
           sex: 'Male'
           new_joinee: 1

Now, if i want to access new_joinee, i have to type as follows.

data.Info[0].new_joinee 
data.Info[2].sex

Just a few examples mentioned here. I want to eliminate this and instead be able to get the output by just typing

Info[0].new_joinee
Info[2].sex

Can someone let me know how can i achieve this. (answered by alexander)

I have one query more on this one. Since, we can see new_joinee is either 0 or 1. I want it to be false for 0 and true for 1. So new data should be as follows.

Info: Array[3]
 >[0]: Object
       name: 'Alex'
       sex: 'Male'
       new_joinee: false
 >[1]: Object
       name: 'Anna'
       sex: 'female'
       new_joinee: true
 >[2]: Object
       name: 'lester'
       sex: 'Male'
       new_joinee: true

I need to dynamically do it. is there a way to achieve this ?

You can assign object property to variable ( var Info = data.Info; )

 var data = { Info: [ { name: 'Alex', sex: 'Male', new_joinee: 0 }, { name: 'Anna', sex: 'female', new_joinee: 1 } ] }; var Info = data.Info; console.log(Info[0].name); console.log(Info[0].new_joinee); console.log(Info[0].sex); console.log(Info[1].name); console.log(Info[1].new_joinee); console.log(Info[1].sex); 

Javascript arrays are assigned by reference . So, if you simply declare a new variable and assign the desired property

var info = data.Info;

voilà, you get a reference to the original property of the object, that you can use directly.

console.log(info[2].name,'is',info[2].sex);

For the second question, .map() is your friend

var info=data.Info.map(function(element){
 element.new_joinee=(element.new_joinee!=0);
 return element;
});

Be aware that you have changed the semantics. Now, info is a copy of the array, not a reference. Eventhough the objects it contains are still references to the original objects.

you could do this instead

   var info = data.Info;
   info.map(function(element){
     element.new_joinee=(element.new_joinee!=0);
     return element;
   });

in this case info and data.Info are references to the same array, the copy that .map() creates is just discarded. But, because the objects are references to the same objects, the changes in the objects' properties are reflected in the original array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM