2

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 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.