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

Viewed 57

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].

3 Answers

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);

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.

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);

Related