我是JavaScript的新手,我有一个要排除2个键的对象:
"age":20
和"university":"HCC"
。
因此,我希望将"name:"Sam"
和"class":55
视为对象中的唯一属性。
var b = {
"name":"Sam",
"age":20,
"university":"HCC",
"class":55
}
答案 0 :(得分:0)
要从对象中排除属性,可以使用简单的delete
:
var b = {
"name":"Sam",
"age":20,
"university":"HCC",
"class":55
};
delete b.age;
delete b.university;
console.log(b);
如果还要检查值是否相同,可以将reduce
与Object.entries
一起使用:
var b = {
"name":"Sam",
"age":20,
"university":"HCC",
"class":55
};
const res = Object.entries(b).reduce((a, [k, v]) => {
if (!((k == "age" && v == 20) || (k == "university" && v == "HCC"))) {
a[k] = v;
}
return a;
}, {});
console.log(res);