Home > Software design >  JavaScript: filter object entries by key
JavaScript: filter object entries by key

Time:02-26

how to filter and return key-value pairs if key is not equal to "targetTime". I have tried with:

const obj = {
  "name": "Rima Biswas",
  "email": "[email protected]",
  "station": "Agartala",
  "targetTime": { "startDate": "2022-02-01T18:30:00.000Z", "endDate": "2022-02-28T18:30:00.000Z" }
};

const entries = Object.entries(obj).filter(([key, value]) => key != "targetTime ");

console.log(entries);

CodePudding user response:

Either

const requiredData = Object.entries(obj).filter(([key, value]) => key !== "targetTime")

Or

const {targetTime, ...restData} = obj;
const requiredData = restData;

CodePudding user response:

Use the code below:

   let obj =   {
        "name": "Rima Biswas",
        "email": "[email protected]",
        "station": "Agartala",
        "targetTime": {                
            "startDate": "2022-02-01T18:30:00.000Z",
            "endDate": "2022-02-28T18:30:00.000Z"
        }};

  Object.fromEntries(Object.entries(obj).filter(([key]) => key !== 'targetTime'));

CodePudding user response:

There is a typo here "targetTime " as pointed out by @evolutionxbox. But you cannot use filter here as filter returns an array, use reduce or forEach as mentioned in last example

Below is another way to do this.

let obj = {
  "name": "Rima Biswas",
  "email": "[email protected]",
  "station": "Agartala",
  "targetTime": {
    "startDate": "2022-02-01T18:30:00.000Z",
    "endDate": "2022-02-28T18:30:00.000Z"
  }
}


const {
  targetTime,
  ...requiredObject
} = obj;
console.log(requiredObject);

With your code you can also do this like below

let obj = {
  "name": "Rima Biswas",
  "email": "[email protected]",
  "station": "Agartala",
  "targetTime": {
    "startDate": "2022-02-01T18:30:00.000Z",
    "endDate": "2022-02-28T18:30:00.000Z"
  }
}

const requiredObj = {};
Object.entries(obj).forEach(([key, value]) => {
  if (key !== "targetTime") {
    requiredObj[key] = value;
  }
});

console.log(requiredObj);

  • Related