根据数组值删除对象属性

时间:2016-07-06 16:00:53

标签: javascript reactjs

我有我的参考数组

const reference = ['prefix', 'suffix', 'student_email']

和我看起来像这样的对象

const obj = {
               'prefix':'John',
               'suffix':'Doe',
               'student_email':'johndoe23@rigly.org',
               'course_code':'PJ4004',
               'professor':'McMillian'
            }

我想删除'course_code'& '教授'因为它不是参考数组的一部分。我怎么能这样做?

预期产出:

const obj = {
               'prefix':'John',
               'suffix':'Doe',
               'student_email':'johndoe23@rigly.org',
            }

我有什么:

reference.map(v => {
    delete obj[v]; // this will delete what I don't want it to delete
});

我怎样才能删除参考数组中不需要/不存在的那些?

1 个答案:

答案 0 :(得分:2)

您可以遍历Object#keys并删除数组中未找到的属性:

const reference = ['prefix', 'suffix', 'student_email']
const obj = {
  'prefix':'John',
  'suffix':'Doe',
  'student_email':'johndoe23@rigly.org',
  'course_code':'PJ4004',
  'professor':'McMillian'
}

Object.keys(obj).forEach(i=>{
  if(reference.indexOf(i) === -1) delete obj[i];
});

console.log(obj);