1

I have a JSON array and another array as follows.

JSON OBJECT

    {
      id: 1,
      name: 'abc',
      email: '[email protected]',
    },
    {
      id: 2,
      name: 'def',
      email: '[email protected]',
    },

SELECTED ARRAY

['id', 'email']

QUESTION

the selected array can have any key value of JSON Object what I want is JSON array should show the specific keys that are selected by a selected array

WHAT I TRIED

  let jsonData = {};
  let arr = [];

  this.selectedExcelTitle.forEach((element) => {
    var columnName = element;
    jsonData[columnName] = this.Users.forEach((e) => {
      return e.element;
    });
  });
  arr.push(jsonData);
2
  • Do you want to filter the "JSON OBJECT" bases on "SELECTED ARRAY"? Commented May 20, 2021 at 15:09
  • yes, based on the question @AnandG. Commented May 20, 2021 at 15:14

1 Answer 1

5

This snippet filters each entry of the given jsonObject (array of objects) so that the resulting filteredJsonObject(array) only contains key-value pairs with a key that is contained in your selectedArray.

var filteredJsonObject = jsonObject.map(function(entry) {
    return selectedArray.reduce(function(res, key) {
        res[key] = entry[key];
        return res;
    }, {});
});
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.