0

I have a very large array of objects that I need the keys remove from. I can't seem to get my head around how to make this happen with list of keys.

https://jsfiddle.net/rgfx_fiddle/cvoz7ygm/15/

const sections = [
            {
                municipality: "Monte De Oca",
                office: "Oficina de la Mujer"
            },
            {
                case_number: "MDO-ABCDEFG",
                identification: "Cédula",
                id_number: "123456789"
            }
];
    
const removeThis = [
    "municipality",
    "id_number"
]


function filter(data) {
  for(var i in data){
    if(removeThis.indexOf(i) != -1){
       delete data[i]; 
    }
  }
  return data;
}

console.log(filter(sections));

1 Answer 1

2

You can use forEach to iterate the objects in sections, with a forEach over the keys in removeThis to delete them from each object:

const sections = [{
    municipality: "Monte De Oca",
    office: "Oficina de la Mujer"
  },
  {
    case_number: "MDO-ABCDEFG",
    identification: "Cédula",
    id_number: "123456789"
  }
];

const removeThis = [
  "municipality",
  "id_number"
]

sections.forEach(obj => {
  removeThis.forEach(k => delete obj[k])
  return obj
})

console.log(sections)

If you don't want to mutate your original objects, you can build new ones using a combination of Object.entries and Object.fromEntries, filtering out the keys from removeThis:

const sections = [{
    municipality: "Monte De Oca",
    office: "Oficina de la Mujer"
  },
  {
    case_number: "MDO-ABCDEFG",
    identification: "Cédula",
    id_number: "123456789"
  }
];

const removeThis = [
  "municipality",
  "id_number"
]

const result = sections.map(
  obj => Object.fromEntries(Object.entries(obj)
    .filter(([k, _]) => !removeThis.includes(k))
  )
)

console.log(result)
console.log(sections)

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

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.