假设我有一个对象:
[
{
'title': "some title"
'channel_id':'123we'
'options': [
{
'channel_id':'abc'
'image':'http://asdasd.com/all-inclusive-block-img.jpg'
'title':'All-Inclusive'
'options':[
{
'channel_id':'dsa2'
'title':'Some Recommends'
'options':[
{
'image':'http://www.asdasd.com' 'title':'Sandals'
'id':'1'
'content':{
...
我想找到id为1的一个对象。是否有类似这样的函数?我可以使用Underscore的_.filter
方法,但我必须从顶部开始并过滤掉。
递归是你的朋友。我更新了函数以考虑属性数组:
function getObject(theObject) {
var result = null;
if(theObject instanceof Array) {
for(var i = 0; i < theObject.length; i++) {
result = getObject(theObject[i]);
if (result) {
break;
}
}
}
else
{
for(var prop in theObject) {
console.log(prop + ': ' + theObject[prop]);
if(prop == 'id') {
if(theObject[prop] == 1) {
return theObject;
}
}
if(theObject[prop] instanceof Object || theObject[prop] instanceof Array) {
result = getObject(theObject[prop]);
if (result) {
break;
}
}
}
}
return result;
}
更新jsFiddle:http://jsfiddle.net/FM3qu/7/
如果要在搜索对象时获取id为1的第一个元素,可以使用此函数:
function customFilter(object){
if(object.hasOwnProperty('id') && object["id"] == 1)
return object;
for(var i=0; i<Object.keys(object).length; i++){
if(typeof object[Object.keys(object)[i]] == "object"){
var o = customFilter(object[Object.keys(object)[i]]);
if(o != null)
return o;
}
}
return null;
}
如果要获取id为1的所有元素,则(所有id为1的元素都存储在结果中):
function customFilter(object, result){
if(object.hasOwnProperty('id') && object.id == 1)
result.push(object);
for(var i=0; i<Object.keys(object).length; i++){
if(typeof object[Object.keys(object)[i]] == "object"){
customFilter(object[Object.keys(object)[i]], result);
}
}
}
对我有用的是这种懒惰的方法,而不是算法上的懒惰;)
if( JSON.stringify(object_name).indexOf("key_name") > -1 ) {
console.log("Key Found");
}
else{
console.log("Key not Found");
}
我通过谷歌搜索找到了类似功能的页面。根据Zach和regularmike提供的工作,我创建了另一个适合我需求的版本。 BTW,teriffic work Zah和regularmike!我会在这里发布代码:
function findObjects(obj, targetProp, targetValue, finalResults) {
function getObject(theObject) {
let result = null;
if (theObject instanceof Array) {
for (let i = 0; i < theObject.length; i++) {
getObject(theObject[i]);
}
}
else {
for (let prop in theObject) {
if(theObject.hasOwnProperty(prop)){
console.log(prop + ': ' + theObject[prop]);
if (prop === targetProp) {
console.log('--found id');
if (theObject[prop] === targetValue) {
console.log('----found porop', prop, ', ', theObject[prop]);
finalResults.push(theObject);
}
}
if (theObject[prop] instanceof Object || theObject[prop] instanceof Array){
getObject(theObject[prop]);
}
}
}
}
}
getObject(obj);
}
它的作用是找到obj
中的任何对象,其属性名称和值与targetProp
和targetValue
匹配,并将其推送到finalResults
数组。这里是玩耍的jsfiddle:https://jsfiddle.net/alexQch/5u6q2ybc/
我为此目的创建了库:https://github.com/dominik791/obj-traverse
您可以像这样使用findFirst()
方法:
var foundObject = findFirst(rootObject, 'options', { 'id': '1' });
现在foundObject
变量存储了对您正在寻找的对象的引用。
使用键和谓词改进了@haitaka答案
function deepSearch (object, key, predicate) {
if (object.hasOwnProperty(key) && predicate(key, object[key]) === true) return object
for (let i = 0; i < Object.keys(object).length; i++) {
if (typeof object[Object.keys(object)[i]] === "object") {
let o = deepSearch(object[Object.keys(object)[i]], key, predicate)
if (o != null) return o
}
}
return null
}
所以这可以调用为:
var result = deepSearch(myObject, 'id', (k, v) => v === 1);
要么
var result = deepSearch(myObject, 'title', (k, v) => v === 'Some Recommends');
这是jsFiddle:http://jsfiddle.net/ktdx9es7
改进了答案以考虑对象内的循环引用。它还显示了到达那里所需的路径。
在这个例子中,我正在搜索我知道在全局对象中某个地方的iframe:
const objDone = []
var i = 2
function getObject(theObject, k) {
if (i < 1 || objDone.indexOf(theObject) > -1) return
objDone.push(theObject)
var result = null;
if(theObject instanceof Array) {
for(var i = 0; i < theObject.length; i++) {
result = getObject(theObject[i], i);
if (result) {
break;
}
}
}
else
{
for(var prop in theObject) {
if(prop == 'iframe' && theObject[prop]) {
i--;
console.log('iframe', theObject[prop])
return theObject[prop]
}
if(theObject[prop] instanceof Object || theObject[prop] instanceof Array) {
result = getObject(theObject[prop], prop);
if (result) {
break;
}
}
}
}
if (result) console.info(k)
return result;
}
运行以下命令:getObject(reader, 'reader')
给出了以下输出和iframe元素:
iframe // (The Dom Element)
_views
views
manager
rendition
book
reader
注意:路径的顺序与reader.book.rendition.manager.views._views.iframe
相反
另一个(有点傻)选项是利用JSON.stringify
的自然递归性质,并在字符串化过程中传递一个在每个嵌套对象上运行的replacer function:
const input = [{
'title': "some title",
'channel_id': '123we',
'options': [{
'channel_id': 'abc',
'image': 'http://asdasd.com/all-inclusive-block-img.jpg',
'title': 'All-Inclusive',
'options': [{
'channel_id': 'dsa2',
'title': 'Some Recommends',
'options': [{
'image': 'http://www.asdasd.com',
'title': 'Sandals',
'id': '1',
'content': {}
}]
}]
}]
}];
console.log(findNestedObj(input, 'id', '1'));
function findNestedObj(entireObj, keyToFind, valToFind) {
let foundObj;
JSON.stringify(input, (_, nestedValue) => {
if (nestedValue && nestedValue[keyToFind] === valToFind) {
foundObj = nestedValue;
}
return nestedValue;
});
return foundObj;
};
如果您已经在使用下划线,请使用_.find()
_.find(yourList, function (item) {
return item.id === 1;
});