gpt4 book ai didi

javascript - 根据数组值删除对象属性

转载 作者:行者123 更新时间:2023-12-02 14:26:05 25 4
gpt4 key购买 nike

我有我的引用数组

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

我的对象看起来像这样

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

我想删除“course_code”和“professor”,因为它不属于引用数组。我怎样才能做到这一点?

预期输出:

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
});

如何才能只删除那些我不需要/不存在于引用数组中的内容?

最佳答案

您可以循环遍历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);

关于javascript - 根据数组值删除对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38228510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com