ramu
ramu

Reputation: 563

get array from the object using map in javascript. but getting array with undefined

I am using map to get the sub part of the array.

var mappingobj = {"custom":[{"head":"202","sub":["302","303"]},{"head":"203","sub":["102"]}],"spec":[]};

var subids = mappingobj.custom.map(function(o, i) {
      if(o.head==202){
       return o.sub;
      }
});

console.log(subids);

I need to get only ["302","303"]. but i am getting the output as [Array[2], undefined].

Upvotes: 4

Views: 60

Answers (3)

HimanshuArora9419
HimanshuArora9419

Reputation: 737

Basic Idea is that map is to get certain value out of array. if you don't return anything in map by default undefined will be return and you will get undefined.So use filter to get desired object and than use map to get desired property of that object

var mappingobj = {"custom":[{"head":"202","sub":["302","303"]},{"head":"203","sub":["102"]}],"spec":[]};

var subids = mappingobj.custom.filter(function(o, i) {
      if(o.head==202 && o.head){
       return o;
      }
}).reduce((acc,elem)=>{acc.push(...elem.sub); return acc;},[]);

console.log(subids);

Upvotes: 3

Niklesh Raut
Niklesh Raut

Reputation: 34914

You can find indexOf of head first and then get sub of mapping.custom

var mappingobj = {"custom":[{"head":"202","sub":["302","303"]},{"head":"203","sub":["102"]}],"spec":[]};
var obj = mappingobj.custom;
var index = obj.map(function (e) { return e.head; }).indexOf("202");
console.log(obj[index].sub);

Upvotes: 0

Sultan Khan
Sultan Khan

Reputation: 318

Hi you can try this.

var mappingobj = {
  "custom": [{
    "head": "202",
    "sub": ["302", "303"]
  }, {
    "head": "203",
    "sub": ["102"]
  }],
  "spec": []
};

var subids = mappingobj.custom.filter(function(o, i) {
  if (o.head == 202) {
    return o.sub;
  }
});

console.log(subids);

Hope this help you.

Upvotes: 0

Related Questions