这是要处理的对象:
var q = {
email: {contains: "noname@hotmail.com"},
name: {contains: "someuser"}
};
我想遍历q的每个键,如果相应的值是具有属性contains
的对象,则将其替换为$regex
。
答案 0 :(得分:2)
相关信息可以在这里找到:JavaScript: Object Rename Key
您可以尝试以下方式:
var q = {
email: {contains: "noname@hotmail.com"},
name: {contains: "someuser"}
};
for(var k in q){
if(q[k].hasOwnProperty('contains')){
Object.defineProperty(q[k], '$regex',
Object.getOwnPropertyDescriptor(q[k], 'contains'));
delete q[k]['contains'];
}
}
console.log(q);
答案 1 :(得分:1)
for(const obj of Object.values(q)) {
obj.$regex = obj.contains;
delete obj.contains;
}
只需遍历q
内的所有值,然后将contains属性复制到$ regex属性中即可。
答案 2 :(得分:0)
var q = {
email: {contains: "noname@hotmail.com"},
name: {contains: "someuser"}
};
Object.keys(q).forEach(k => {
if (typeof q[k].contains != 'undefined'){
q[k].$regex = q[k].contains;
delete q[k].contains;
}
})
console.log(q);
使用Es 6功能的其他版本
const renameProp = (
oldProp,
newProp,
{ [oldProp]: old, ...others }
) => {
return {
[newProp]: old,
...others
};
};
let q = {
email: {contains: "noname@hotmail.com"},
name: {contains: "someuser"}
};
let newObj = {}
for (let propName in q) {
newObj[propName] = renameProp("contains","$regex",q[propName])
}
console.log(newObj)
答案 3 :(得分:0)
要首先遍历对象键,您必须先获取它们,这是一种简单的方法
const keys = Object.keys(q); // ["email", "name"]
现在遍历我们得到的数组并执行正则表达式测试;
keys.forEach(key => {
let value = q[key].contains;
// create $regex and assign value
// remove .contains
})
答案 4 :(得分:0)
var q = {
email: {
contains: "noname@hotmail.com"
},
name: {
contains: "someuser"
},
asdf: "asdf"
};
Object.keys(q).forEach(function(item, index) {
if (typeof q[item] == "object" && q[item].contains) {
q[item].$regex = q[item].contains;
delete q[item].contains;
}
})
答案 5 :(得分:0)
您可以遍历对象,然后将contains
属性的当前值放入$regex
中,然后删除contains
属性。
下面是工作代码:
var q = {
email: {
contains: "noname@hotmail.com"
},
name: {
contains: "someuser"
}
};
for (var i of Object.values(q)) {
if (i.hasOwnProperty("contains")) {
i.$regex = i.contains;
delete i.contains;
}
}
console.log(q);