skip to Main Content

I have a key and value pair format, i want to filter all the values which are in array into a single array

const holiday_expenses = {
  food: [{name: "abc", place: "xyz"}],
  travel: [{name: "abcd", place: "xyz1"}],
  accommodation: [{name: "xysz", place: "xyz2"}]
}

Expected Result:

result : [{name: "abc", place: "xyz"}, {name: "abcd", place: "xyz1"}, {name: "xysz", place: "xyz2"}]

2

Answers


  1. Just get all the object’s values and flatten them:

    const result = Object.values(holiday_expenses).flat();
    

    Complete snippet:

    const holiday_expenses = {
      food: [{name: "abc", place: "xyz"}],
      travel: [{name: "abcd", place: "xyz1"}],
      accommodation: [{name: "xysz", place: "xyz2"}]
    };
    
    const result = Object.values(holiday_expenses).flat();
    
    console.log(result);
    Login or Signup to reply.
  2. import "_" from lodash;
    cosnt obj = {/...whatever you have/}
    const res = _.values(obj);

    Check "lodash", I believe it can make you life better. https://lodash.com/docs/
    There are a lots of helper functions to manipulate arrays and objects.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search