Array map & reduce shows undefined value

Viewed 102

I have two arrays named headersMap and selected_arr as follows

headersMap: [
    {
      text: "#",
      align: "center",
      sortable: true,
      value: "id",
      align: "start",
      width: "1%",
    },
    {
      text: "Name",
      align: "center",
      sortable: true,
      value: "name",
      align: "start",
    },
    {
      text: "Company",
      align: "center",
      sortable: true,
      value: "company",
      align: "start",
    }
 ]
selected_arr: ['id', 'company']

What I have tried was as follows:

let jsonObject = this.headersMap;
let selectedArray = this.selected_arr;
let filteredJsonObject = jsonObject.map(function(entry) {
    return selectedArray.reduce(function(res, key) {
        res[key] = entry[key];
        return res;
    }, {});
});

console.log(filteredJsonObject);

output:

[
    {
      #: undefined
      company: undefined
    }
]

QUESTION: what I want is to reduce the headersMap by selected_arr, the output should be as follows:

[
    {
      text: "#",
      align: "center",
      sortable: true,
      value: "id",
      align: "start",
      width: "1%",
    },
    {
      text: "Company",
      align: "center",
      sortable: true,
      value: "company",
      align: "start",
    }
 ]
1 Answers

Use Array#filter:

const 
  headersMap = [
    { text: "#", align: "center", sortable: true, value: "id", align: "start", width: "1%" },
    { text: "Name", align: "center", sortable: true, value: "name", align: "start" },
    { text: "Company", align: "center", sortable: true, value: "company", align: "start" }
  ],
  selected_arr = ['id', 'company'];

const filtered = headersMap.filter(({ value }) => selected_arr.includes(value));

console.log(filtered);

Related