2

I would like to know how to remove multiple keys in object javascript. how to remove the date keys in the obj.

var obj ={
  "id": "1",
  "cn": "TH",
  "curr": "THB",
  "10-02-2020": "10,11",
  "12-01-2019": "2,5"
}

var result = filterkeys(obj,["id","cn","curr"]);

function filterkeys(obj,arr){
   arr.forEach(function(key) {
    delete !obj[key];
  });
  return obj;
}

Expected Output:

{
  "id": "1",
  "cn": "TH",
  "curr": "THB"
}
2

2 Answers 2

3

You need to go the other way around - iterate over all keys of the object, and if it isn't in the arr, delete it:

var obj ={
  "id": "1",
  "cn": "TH",
  "curr": "THB",
  "10-02-2020": "10,11",
  "12-01-2019": "2,5"
}

var result = filterkeys(obj,["id","cn","curr"]);

function filterkeys(obj,arr){
  for (const key of Object.keys(obj)) {
    if (!arr.includes(key)) {
      delete obj[key];
    }
  }
  return obj;
}

console.log(result);

Or, without delete (probably better to avoid delete when possible - it's good to avoid mutation) - map the keys array to construct a new object with Object.fromEntries:

var obj ={
  "id": "1",
  "cn": "TH",
  "curr": "THB",
  "10-02-2020": "10,11",
  "12-01-2019": "2,5"
};
const filterkeys = (obj,arr) => Object.fromEntries(
  arr.map(key => [key, obj[key]])
);

var result = filterkeys(obj,["id","cn","curr"]);

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

0

Use Object.assign and add the entries by required keys map.
Alternatively you can use Reflect.deleteProperty to remove unwanted keys.

var obj = {
  id: "1",
  cn: "TH",
  curr: "THB",
  "10-02-2020": "10,11",
  "12-01-2019": "2,5"
};

const filterkeys = (obj, keys) =>
  Object.assign({}, ...keys.map(key => ({ [key]: obj[key] })));

var result = filterkeys(obj, ["id", "cn", "curr"]);

console.log(result);

const filterkeys2 = (obj, keys) => {
  Object.keys(obj).forEach(key => !keys.includes(key) && Reflect.deleteProperty(obj, key))
  return obj;
};
var result2 = filterkeys2(obj,["id","cn","curr"]);
console.log(result2);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.