Get an array from an object using a map in javascript. but getting an array with undefined

I use a map to get a subset 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);
Run codeHide result

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

+4
source share
3 answers

The main idea is that the map should get a specific value from the array. if you do not return anything on the map by default, undefined will return and you will get undefined. Use the filter to obtain the desired object and use the map to obtain the desired property of this 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);
Run codeHide result
+3
source

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);
Run codeHide result

Hope this helps you.

0
source

indexOf of head, 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);
Hide result
0

Source: https://habr.com/ru/post/1689886/


All Articles