Lulceltech
Lulceltech

Reputation: 1702

Filtering an object to contain only keys that exist in an array of objects

my brain is currently melting on a better way to do this that follows my eslint settings that said what im trying to do is remove keys from an object that don't exist in an array of objects and I have code that currently works but it makes eslint mad so I can't use this:

fieldData = recipeOutputFields(z, bundle);

  return promise.then((response) => response.json.response.map((item) => {
    const temp = item;

    temp.id = temp.customer_id;

    const diff = {};

    for (const [key, value] of Object.entries(temp)) {
      fieldData.some((el, val) => {
        if (el.key === key) {
          diff[key] = value;
        }
      });
    }

That said here's some samples of what im working with

let theObjectINeedToRemoveKeysFrom = {
   key1: "test",
   key2: "test2",
   key3: "test",
   key4: "test",
}

let theArrayOfObjectsToFilterBy = [
    {
       key: "key1",
       type: "string",
    },
    {
       key: "key2",
       type: "string",
    },
    {
       key: "key4",
       type: "int",
    },
]

The expected output would be something like:

let expectedResult = {
   key1: "test",
   key2: "test2",
   key4: "test",
}

Since key3 didn't exist in the array of objects it would be removed from the object. Dose anyone have any suggestions for how to convert and simplify my function that does this to something that eslint likes?

The ES Lint Errors: enter image description here

Upvotes: 0

Views: 78

Answers (1)

James
James

Reputation: 22227

You can use Object.fromEntries to wrap the Object.entries array back into an object.

let temp = {
   key1: "test",
   key2: "test2",
   key3: "test",
   key4: "test",
};

let fieldData = [
    {
       key: "key1",
       type: "string",
    },
    {
       key: "key2",
       type: "string",
    },
    {
       key: "key4",
       type: "int",
    },
];

const diff = Object.fromEntries(
  Object.entries(temp).filter(([k, v]) => 
    fieldData.some(({key}) => k === key)
  )
);

console.log(diff);

Upvotes: 1

Related Questions