简体   繁体   中英

return object with property value

I have the following data:

  var data = { 
    someData : [
      {
        title: "something",
        color: "red",
        moreInfo : [
          {
            title: "something else",
            color: "orange",
            moreInfo : [
              {
                title: "something more",
                color: "green",
                moreInfo : [
                  {
                    title: "another title",
                    color: "yellow"
                  }
                ]
              }
            ]
          },
          {
            title: "blah blah",
            color: "blue"
          }
        ]
      },
      {
        title: "something cool",
        color: "black"
      }
    ]
  };

I want to run a function to return the object with the property that matches a certain value. Currently I have this:

  var result = data.filter(obj => {
    return obj.title === "something more";
  });

I want the function to be able to iterate through every object and nested object and return the object with that value. So in this case I would like for it to return:

{
  title: "something more",
  color: "green",
  moreInfo: [
    {
     title: "another title",
     color: "yellow"
    }
 ]
}

If someone could please help me with this. It seems simple enough but I have spent way too much time on this.Thank you!

You can filter array recursively using below-mentioned function:

  var filter = (array) => {
    array.filter(obj => {
     if(obj.title === "something more"){
     return obj     
   }
    if(obj.moreInfo){
     filter(obj.moreInfo)
    }
    });
  } 

Use a recursive function like this:

 function dig(obj, func){ let v; if(obj instanceof Array){ for(let i=0,l=obj.length; i<l; i++){ v = obj[i]; if(typeof v === 'object'){ dig(v, func); } else{ func(v, i, obj); } } } else{ for(let i in obj){ v = obj[i]; if(typeof v === 'object'){ dig(v, func); } else{ func(v, i, obj); } } } } // I don't like your sytax - but didn't fix it var data = { someData: [ { title: "something", color: "red", moreInfo: [ { title: "something else", color: "orange", moreInfo: [ { title: "something more", color: "green", moreInfo: [ { title: "another title", color: "yellow" } ] } ] }, { title: "blah blah", color: "blue" } ] }, { title: "something cool", color: "black" } ] }; function getObjByTitle(object, title){ let obj = false; dig(object, (v, k, o)=>{ if(k === 'title' && v === title){ obj = o; } }); return obj; } console.log(getObjByTitle(data, 'something more'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM