0

I would like to know how to remove particular key in object array javascript. In the array object obj, if the id is null remove the key in javascript

var obj = [{
  id: 1,
  field: "finance"
}, {
  id: null,
  field: "service}, {
  id: 2,
  field: "information"
}]

functionremoveKey(arrobj) {
  return arrobj.filter(e => {
    if (e.id == null) {
      delete e.id;
    }
  }
}

var result = removeKey(obj);

Expected Output:

{
  { id: 1, field: "finance" },
  { field: "service" },
  { id: 2, field: "information" }
]
3
  • 3
    That's not what .filter() is meant to be used for/as. You either want .forEach() or .map() Commented May 20, 2020 at 9:35
  • You're missing a quote after service. Is it a typo? Commented May 20, 2020 at 9:35
  • Try this obj.forEach(e => { if (e.id === null) { delete e.id } }); Commented May 20, 2020 at 9:46

3 Answers 3

1

You can make use of map for this:

var obj = [{ id: 1, field: "finance"}, { id: null, field: "service"}, { id: 2, field: "information"}]
result = obj.map(val=>val.id ? val : (delete val.id, val));
console.log(result);

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

Comments

0

As Andreas mentions you'll want to iterate over the elements and remove the key rather than trying to filter the whole array. Something like the following would work:

var arr = [
    { id: 1, field: "finance" },
    { id: null, field: "service" },
    { id: 2, field: "information" }
];

function removeKey(arr) {
    arr.forEach(element => {
        if (element.id == null) {
            delete element.id;
        }                
    });
}

removeKey(arr);
console.log(arr);

Comments

0

If you don't want to mutate the source, you can use the following:

var obj = [{
  id: 1,
  field: "finance"
}, {
  id: null,
  field: "service"
}, {
  id: 2,
  field: "information"
}]

function removeKey(arrobj, keyname) {
  return arrobj.map(e => 
    Object.fromEntries(
      Object.entries(e).filter(
        ([k, v]) => v !== null || keyname !== k
      )
    )
  )
}

console.log(removeKey(obj, 'id'));

It makes use of the Object.fromEntries method, which is relatively new, if your environment doesn't support it, use this instead:

var obj = [{
  id: 1,
  field: "finance"
}, {
  id: null,
  field: "service"
}, {
  id: 2,
  field: "information"
}]

function removeKey(arrobj, keyname) {
  return arrobj.map(e => 
    Object
      .entries(e)
      .filter(([k, v]) => v !== null || keyname !== k)
      .reduce((obj, [k, v]) => (obj[k] = v, obj), {})
  )
}

console.log(removeKey(obj, 'id'));

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.