我有一个嵌套的对象,如下所示:
let obj = {
_id:{}
person:{
$search:{fname:true}
_id:{},
fname:{}
},
code:{},
vnvEmpName:{}
}
我必须在此搜索 $ search 关键字并获取其中包含 fname 的密钥,在这种情况下,它还可以包含多个密钥我必须检索所有这些。
我试过这样的事情:
function findById(obj, id) {
var result;
for (var p in obj) {
if (obj.id === id) {
return obj;
} else {
if (typeof obj[p] === 'object') {
result = findById(obj[p], id);
if (result) {
return result;
}
}
}
}
return result;
}
如果对象是这样的:
let obj = {
_id: {},
person: {
$search: {
lname: true
},
_id: {},
fname: {},
soomething:{
$search: {
fname: true
},
}
},
code: {},
$search: {
mname: true
},
vnvEmpName: {}
} 我想检索每个块的$ search内的所有属性。
但我不知道如何将密钥放入特定密钥中,因为我对javascript很新。
答案 0 :(得分:0)
要获取密钥,只需使用{{1}} MDN Object.keys
即可您也可以使用lodash获得相同的结果
答案 1 :(得分:0)
需要递归搜索对象
let obj = {
_id: {},
person: {
$search: {
fname: true
},
_id: {},
fname: {}
},
code: {},
vnvEmpName: {}
}
function findById(obj, id) {
var result = "";
// iterate the object using for..in
for (var keys in obj) {
// check if the object has any property by that name
if (obj.hasOwnProperty(keys) && typeof obj[keys] === 'object') {
// if the key is not undefined get it's value
if (obj[keys][id] !== undefined) {
result = (obj[keys][id])
} else {
// else again call the same function using the new obj value
findById(obj[keys], id)
}
}
}
return result;
}
console.log(findById(obj, 'fname'))

答案 2 :(得分:0)
您可以使用以下功能:
const objectifier = function (splits, create, context) {
let result = context;
for (let i = 0, key; result && (key = splits[i]); i += 1) {
if (key in result) { result = result[key]; } else {
result = create
? result[key] = {}
: undefined;
}
}
return result;
};
看一下下面的例子:
let obj = {
'_id': {aa: 'aa'},
'person': {
'$search': {
'fname': true
},
'_id': {'bb': 'bb'},
'fname': {'cc': 'cc'}
},
'code': {'dd': 'dd'},
'vnvEmpName': {'name': 'sdsdd'}
}
const objectifier = function (splits, create, context) {
let result = context;
for (let i = 0, key; result && (key = splits[i]); i += 1) {
if (key in result) { result = result[key]; } else {
result = create
? result[key] = {}
: undefined;
}
}
return result;
};
console.log(objectifier('person.$search'.split('.'), false, obj));
// { fname: true }