我有这个对象
Object {
"87291": "valid",
"1873681927": "valid",
"nwq89j8jw0qj9": "valid",
"oVFYfWIUOsONE6JyMGYAbnsPMAr1": "valid",
}
我要做的是根据键值删除对象并以数组形式返回。
我使用了以下代码:
let attay = {
"87291": "valid",
"1873681927": "valid",
"nwq89j8jw0qj9": "valid",
"oVFYfWIUOsONE6JyMGYAbnsPMAr1": "valid",
}
let aar = Object.entries(attay)
attay = Object.keys(attay)
for(var i = 0; i < attay.length; i++) {
if(attay[i] == 'oVFYfWIUOsONE6JyMGYAbnsPMAr1'){
console.log("found "+attay[i]+" at "+i)
aar.splice(i, 1);
console.log(aar)
}else{
console.log("NOT found at "+i)
}
}
这段代码可以正常工作,但是remove元素之后的输出是这样的
Array [
Array [
"87291",
"valid",
],
Array [
"1873681927",
"valid",
],
Array [
"nwq89j8jw0qj9",
"valid",
],
]
预期输出应类似于
Array [
"87291": "valid",
"1873681927": "valid",
"nwq89j8jw0qj9": "valid",
]
答案 0 :(得分:4)
也许我误会了,但似乎您对此过于复杂了。您要从对象中删除属性吗?
let arr = {
"87291": "valid",
"1873681927": "valid",
"nwq89j8jw0qj9": "valid",
"oVFYfWIUOsONE6JyMGYAbnsPMAr1": "valid",
}
let removeKey = "oVFYfWIUOsONE6JyMGYAbnsPMAr1"
delete arr[removeKey]; // Remove the property
console.log(arr);
答案 1 :(得分:1)
如果相对较新的entries
(和fromEntries
)的运行时还可以,那么您可以轻松获得所需的内容。 (猜测您实际上是针对对象输出,而不是基于问题语法的数组)。
let attay = {
"87291": "valid",
"1873681927": "valid",
"nwq89j8jw0qj9": "valid",
"oVFYfWIUOsONE6JyMGYAbnsPMAr1": "valid",
}
let removeKey = "oVFYfWIUOsONE6JyMGYAbnsPMAr1"
let pairs = Object.entries(attay).filter(e => e[0] != removeKey)
const obj = Object.fromEntries(pairs);
console.log(obj)
答案 2 :(得分:1)
答案 3 :(得分:0)
如果密钥与适当性匹配,则可以这样使用delete
:
const obj = {
"87291": "valid",
"1873681927": "valid",
"nwq89j8jw0qj9": "valid",
"oVFYfWIUOsONE6JyMGYAbnsPMAr1": "valid",
}
const key = "87291";
delete obj[key]
console.log(obj)
答案 4 :(得分:0)
您可以使用简单的fromEntries
来避免受较少支持的reduce
。
let attay = {
"87291": "valid",
"1873681927": "valid",
"nwq89j8jw0qj9": "valid",
"oVFYfWIUOsONE6JyMGYAbnsPMAr1": "valid",
};
const remove = "oVFYfWIUOsONE6JyMGYAbnsPMAr1";
const res = Object.entries(attay).reduce((acc, [k, v]) => k == remove ? acc : (acc[k] = v, acc), {});
console.log(res);