Home > Blockchain >  Filter Object based on Keys and compare with array
Filter Object based on Keys and compare with array

Time:03-03

I currently have an object containing key with multiple values.

I also have an array containing a simple key check i.e. ["random", "three"].

I want to return mainData but only with the object and the data from whats in the array i.e. ["random", "three"]

Current Code:

const mainData = {
    random: {
        name: "Random Entity",
        date: "05/04/2022",
        startTime: "19:00",
        finishTime: "00:00",
    },
    one: {
        name: "One Entity",
        date: "16/04/2022",
        startTime: "16:00",
        finishTime: "20:00",
    },
    three: {
        name: "Three Entity",
        date: "19/04/2022",
        startTime: "10:00",
        finishTime: "11:00",
    },
};

export default mainData;

Desired Output

const mainData = {
    random: {
        name: "Random Entity",
        date: "05/04/2022",
        startTime: "19:00",
        finishTime: "00:00",
    },
    three: {
        name: "Three Entity",
        date: "19/04/2022",
        startTime: "10:00",
        finishTime: "11:00",
    },
};

Attempt:

let filterKey = 'random';
const result = Object.entries(mainData).filter(([k, v]) => k== filterKey);

This works only as a single search, not an array search.

CodePudding user response:

Map the array to an entries array ([[key,val],[key,val],...]) and pass it through Object.fromEntries()

const mainData = {"random":{"name":"Random Entity","date":"05/04/2022","startTime":"19:00","finishTime":"00:00"},"one":{"name":"One Entity","date":"16/04/2022","startTime":"16:00","finishTime":"20:00"},"three":{"name":"Three Entity","date":"19/04/2022","startTime":"10:00","finishTime":"11:00"}}

const filters = ["random", "nope", "three"]

const result = Object.fromEntries(
  filters
    .filter(
      key => key in mainData // only include keys that exist in mainData
    ) 
    .map(
      key => [ key, mainData[key] ]
    )
)

console.log(result)
.as-console-wrapper { max-height: 100% !important; }

CodePudding user response:

If you know the keys you'd like to exclude you can use this approach:

const mainData = { random: { name: "Random Entity", date: "05/04/2022", startTime: "19:00", finishTime: "00:00", }, one: { name: "One Entity", date: "16/04/2022", startTime: "16:00", finishTime: "20:00", }, three: { name: "Three Entity", date: "19/04/2022", startTime: "10:00", finishTime: "11:00" } };

const {one, ...desiredData} = mainData;

console.log( desiredData );

  • Related