Home > Software design >  How to delete key from object in React Native javascript
How to delete key from object in React Native javascript

Time:08-05

I have an object named "colors" which have keys like

{
"white":"#FFFFFF",
"black":"#000000",
"red":"FF0000"
}

In some of the conditions i want all colors except the "white" color

CodePudding user response:

const source = {
"white":"#FFFFFF",
"black":"#000000",
"red":"FF0000"
};

const target = {...source};
delete target["white"]

Typescript Version:

const source = {
"white":"#FFFFFF",
"black":"#000000",
"red":"FF0000"
};

const target: Partial<typeof source> = {...source};
delete target["white"]

CodePudding user response:

let color = {
"white":"#FFFFFF",
"black":"#000000",
"red":"FF0000"
}

let filteredColor = Object.keys(color)
    .filter((key) => !key.includes("white"))
    .reduce((obj, key) => {
        return Object.assign(obj, {
          [key]: color[key]
        });
  }, {});

using the filter and reduce you can filter out the result

CodePudding user response:

delete source["colourname"]

  • Related