返回具有属性值的对象

时间:2020-02-28 02:52:40

标签: javascript

我有以下数据:

  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"
      }
    ]
  };

我想运行一个函数以返回具有与某个值匹配的属性的对象。 目前,我有这个:

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

我希望函数能够遍历每个对象和嵌套的对象并返回具有该值的对象。 因此,在这种情况下,我希望它返回:

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

如果有人可以帮助我。看起来很简单,但我花了太多时间在此上。谢谢!

2 个答案:

答案 0 :(得分:2)

您可以使用下面提到的函数递归过滤数组:

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

答案 1 :(得分:0)

使用这样的递归函数:

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'));