首页 > 解决方案 > 如何以值路径作为参考遍历数组

问题描述

我真的不知道如何表达我想要的,但我会尝试。

所以,我有object一个array内部名称为 的recipes,我从 my 收到的API,并且 avaluePath是一个object

目的

{
  recipes: [
    {
      test: {
        items: [
          {
            type: 'test1',
          }
        ]
      }
    }
  ]
}

价值路径

{
  "allRecipes": {
    "array": "recipes",
    "values": {
      "allTypes": {
        "array": "test",
        "values": {
          "type": "type"
        }
      }
    }
  }
}

简而言之,我必须做的是动态地遍历array recipesvaluePath因为arrayvalues可以改变。我真的不知道如何更好地解释它以及如何迭代深度嵌套的思想,并将objects/array'savaluePath作为参考来查找values.

到目前为止我尝试过的...

 export const test = (object, valuePath) => {
  for (const prop in valuePath) {
    object = object[valuePath[prop].array]; // find the array

    if (Array.isArray(object)) {
      object.forEach(objRef => {
        console.log('valueRef', objRef);
      });
    }

    console.log('props->', valuePath[prop].values); // find the values
  }
};

我想我需要一个递归,但不知道怎么做。

标签: javascriptarraysobjectrecursionecmascript-6

解决方案


如果我理解您的问题,这可能是一个实现......如果您使用数据和路径运行它,它将返回test1.

// INPUTS
const data = {
  recipes: [
    {
      test: {
        items: [
          {
            type: 'test1',
          }
        ]
      }
    }
  ]
}

const path = {
  "allRecipes": {
    "array": "recipes",
    "values": {
      "allTypes": {
        "array": "test",
        "values": {
          "type": "type"
        }
      }
    }
  }
}



// this is just an helper method for arrays...
Array.prototype.first = function () { return this[0] }


// this is an helper function that tells us whether
// a path object is still traversable.
// from what I understood, if it contains an `array` property
// we should follow it...
const isTraversable = path => !!path.array


// this is the actual implementation of the algorithm
const traverse = (data, path) => {
  const nextPath = Object.values(path).first()
  
  if ( isTraversable(nextPath) ) {
    const array = data[nextPath.array]

    // I noticed that at a certain point in the data object,
    // we need to traverse an array, and in another it is an
    // object with an `items` property.
    // this next lines helps determine how go down
    const nextData = Array.isArray(array) ? array.first() : array.items

    // we recurse on the traversed data and path
    return traverse(nextData, nextPath.values)
  }

  return data.first()[path.type]
}

console.log(traverse(data, path))


推荐阅读