javascript - 如何以值路径作为参考遍历数组
问题描述
我真的不知道如何表达我想要的,但我会尝试。
所以,我有object
一个array
内部名称为 的recipes
,我从 my 收到的API
,并且 avaluePath
是一个object
:
目的
{
recipes: [
{
test: {
items: [
{
type: 'test1',
}
]
}
}
]
}
价值路径
{
"allRecipes": {
"array": "recipes",
"values": {
"allTypes": {
"array": "test",
"values": {
"type": "type"
}
}
}
}
}
简而言之,我必须做的是动态地遍历array recipes
,valuePath
因为array
和values
可以改变。我真的不知道如何更好地解释它以及如何迭代深度嵌套的思想,并将objects/array's
avaluePath
作为参考来查找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
}
};
我想我需要一个递归,但不知道怎么做。
解决方案
如果我理解您的问题,这可能是一个实现......如果您使用数据和路径运行它,它将返回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))
推荐阅读
- python - IndexError:列表索引超出范围 - 从 cli 打开文件 - argv [1]
- google-analytics - 如何向此 Google Analytics 查询添加“过滤器”?
- c# - 只有在单击按钮后我才能开始更新(Unity 和编码中的新手)
- excel - 使用 Instr 复制工作表,同时忽略隐藏工作表
- python - 将 Flask Stadout 重定向到 Guinicorn 日志文件
- java - 如何使用 Dagger 2 将上下文传递给适配器?
- git - 从上游获取并撤消我在来源中的所有提交
- angular - 未定义角度标识符“playerPhoto”。'' 不包含这样的成员
- javascript - HTML/CSS 样式化重复元素的有效方式?
- python - 搜索程序中具有相同值的不敏感键