
Harry
Nehmen wir an, ich habe ein Objekt:
[
{
'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':{
...
I want to find the one object where the id is 1. Is there a function for something like this? I could use Underscore’s _.filter
method, but I would have to start at the top and filter down.

Zach
Recursion is your friend. I updated the function to account for property arrays:
function getObject(theObject) {
var result = null;
if(theObject instanceof Array) {
for(var i = 0; i < theObject.length; i++) {
result = getObject(theObject[i]); if (Ergebnis) {break; } } } else { for(var prop in theObject) { console.log(prop + ': ' + theObject[prop]); if(prop == 'id') { if(theObject[prop] == 1) { das Objekt zurückgeben; } } if(dasObjekt[prop] Instanz des Objekts || das Objekt[prop] instanceof Array) { result = getObject(theObject[prop]); if (Ergebnis) {break; } } } } Ergebnis zurückgeben; }
aktualisierte jsFiddle: http://jsfiddle.net/FM3qu/7/
Was für mich funktioniert hat, war dieser faule Ansatz, nicht algorithmisch faul;)
if( JSON.stringify(object_name).indexOf("key_name") > -1 ) {
console.log("Key Found");
}
else{
console.log("Key not Found");
}

haitaka
Wenn Sie das erste Element erhalten möchten, dessen ID 1 ist, während das Objekt durchsucht wird, können Sie diese Funktion verwenden:
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;
}
Wenn Sie alle Elemente erhalten möchten, deren ID 1 ist, dann (alle Elemente, deren ID 1 ist, werden im Ergebnis gespeichert, wie Sie sehen):
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);
}
}
}

Bestimmte Leistung
Eine andere (etwas alberne) Option besteht darin, die natürlich rekursive Natur von auszunutzen JSON.stringify
und übergebe es a Ersatzfunktion die während des Stringifizierungsprozesses auf jedem verschachtelten Objekt ausgeführt wird:
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(entireObj, (_, nestedValue) => {
if (nestedValue && nestedValue[keyToFind] === valToFind) {
foundObj = nestedValue;
}
return nestedValue;
});
return foundObj;
};

Julian Pinzaru
Verbesserte @haitaka-Antwort unter Verwendung des Schlüssels und des Prädikats
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++) {
let value = object[Object.keys(object)[i]];
if (typeof value === "object" && value != null) {
let o = deepSearch(object[Object.keys(object)[i]], key, predicate)
if (o != null) return o
}
}
return null
}
Dies kann also aufgerufen werden als:
var result = deepSearch(myObject, 'id', (k, v) => v === 1);
oder
var result = deepSearch(myObject, 'title', (k, v) => v === 'Some Recommends');
Hier ist die Demo: http://jsfiddle.net/a21dx6c0/
BEARBEITET
Auf die gleiche Weise können Sie mehr als ein Objekt finden
function deepSearchItems(object, key, predicate) {
let ret = [];
if (object.hasOwnProperty(key) && predicate(key, object[key]) === true) {
ret = [...ret, object];
}
if (Object.keys(object).length) {
for (let i = 0; i < Object.keys(object).length; i++) {
let value = object[Object.keys(object)[i]];
if (typeof value === "object" && value != null) {
let o = this.deepSearchItems(object[Object.keys(object)[i]], key, predicate);
if (o != null && o instanceof Array) {
ret = [...ret, ...o];
}
}
}
}
return ret;
}

Alex Quan
Ich habe diese Seite beim Googeln nach ähnlichen Funktionen gefunden. Basierend auf der Arbeit von Zach und regularmike habe ich eine andere Version erstellt, die meinen Bedürfnissen entspricht.
Übrigens, tolle Arbeit Zah und Regularmike! Ich poste den Code hier:
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);
}
Was es tut, ist, dass es jedes Objekt darin findet obj
mit Eigenschaftsname und Wert passend zu targetProp
und targetValue
und wird es auf die schieben finalResults
Reihe. Und hier ist die jsfiddle zum Herumspielen:
https://jsfiddle.net/alexQch/5u6q2ybc/

Dominik791
Ich habe zu diesem Zweck eine Bibliothek erstellt: https://github.com/dominik791/obj-traverse
Sie können verwenden findFirst()
Methode so:
var foundObject = findFirst(rootObject, 'options', { 'id': '1' });
Und nun foundObject
Variable speichert einen Verweis auf das gesuchte Objekt.
9149500cookie-checkSuchen nach Schlüssel tief in einem verschachtelten Arrayyes