假设我们有一个对象:
message {
diff: {
cat: "Tabby"
name: "Meow Meow"
}
}
您可以使用hasOwnProperty()检查重复项并删除重复项吗?示例
for (key in message.diff) {
//outputs every change when all keys are updated
if (message.diff.hasOwnProperty(key)){
this.uniqueArray.push(key);
}
}
编辑:我意识到可能会混淆我想要谈论的内容。
我有一个函数,它可以监听任何可以更新的表单元素,将输入记录到控制台中。它主要是监听属性名称。它将自身输出到数组,该数组可能包含也可能不包含重复的名称。
如果我们多次更新表单字段,则会变为:
Current Output: ['name', 'name', 'name', 'cat']
Desired Ouput: ['name', 'cat']
答案 0 :(得分:1)
检查数组
中是否存在对象键for (key in message.diff) {
//outputs every change when all keys are updated
if (message.diff.hasOwnProperty(key) && this.uniqueArray.indexOf(key) == -1){
this.uniqueArray.push(key);
}
}
答案 1 :(得分:0)
您可以使用Object.keys()
,Array.prototype.filter()
,Array.prototype.includes()
来检查对象的属性是否为数组元素Array.prototype.push()
,展开元素
var message = {
diff: {
cat: "Tabby",
name: "Meow Meow"
}
}
var arr = ["name", "cat"];
arr.push(...Object.keys(message.diff).filter(function(diff) {return !arr.includes(diff)}));
console.log(arr);
var message = {
diff: {
lion: "Tabby",
tiger: "Meow Meow"
}
}
arr.push(
...Object.keys(message.diff)
.filter(function(diff) {return !arr.includes(diff)}))
console.log(arr);