gpt4 book ai didi

javascript - 如何在嵌套数组中查找属性并返回其位置

转载 作者:行者123 更新时间:2023-12-02 17:33:58 27 4
gpt4 key购买 nike

仅使用 JavaScript,有没有办法在一个数组中定位一个属性,而该属性本身又在另一个数组中,并返回其“路径”?

想象一个嵌套数组的分层组,就像这个例子一样:

    var bigBox = [  

mediumBoxA = [
smallBoxA = [
toyA = { toyId : "Blue Ball"},
toyb = { toyId : "Pink Ball"}
],

smallBoxB = [
toyA = { toyId : "Girl Doll"},
toyB = { toyId : "Boy Doll"}
],
],

mediumBoxB = [
smallBoxA = [
toyA = { toyId : "Batman"},
toyB = { toyId : "Superman"}
],

smallBoxB = [
toyA = { toyId : "Lego"},
toyB = { toyId : "Soldier"}
],
]

];

鉴于此,在控制台我希望能够搜索例如:“ bat 侠”并得知它是位于bigBox >mediumBoxB >smallBoxA > toyA。再次,我正在寻找一个仅 JS 的解决方案以及可以在控制台上实现的东西。不涉及 HTML。

现在,我知道我只能通过索引号,我在每个数组上使用了标签,例如“smallBox”、“toyB”等......出于解释目的。

谢谢大家!

最佳答案

我实现了一个递归函数,它找到路径并将其作为数组返回:

/**
* Finds an value and returns the path of nested variable names
*
* @param {obj} The object to search in
* @param {search} The value to search for
* @param {variables} The relevant variables names or the context object
* @param {context} The context object in which to search the variable names
*
* @return The found path as an array or null if nothing was found
*/
function getPath(obj, search, variables, context) {

if(context === undefined) {
context = window;
}

if(variables === undefined) {
variables = window;
}
if(!Array.isArray(variables)) {
// if variables is an object, this object is the context
context = variables;
// copy the keys to the variables array
variables = [];
for(var key in context) {
if(context.hasOwnProperty(key)) {
try {
// try to read property
context[key];
// push key to variable names
variables.push(key);
} catch(e) {
// some properties of the window object cannot be read
}
}
}
}

function getVariableName(variable) {
for(var i = 0; i < variables.length; i++) {
var name = variables[i];
if(context[name] === variable) {
// return variable name
return name;
}
}
return null;
}

function _getPath(variable, path) {
if(typeof variable === 'object') {
var name = getVariableName(variable);
if(name) {
var pathCopy = path.slice(0);
pathCopy.push(name);
for(var key in variable) {
// recursive call of _getPath
var returnedPath = _getPath(variable[key], pathCopy);
if(returnedPath) {
return returnedPath;
}
}
}
} else if(variable === search) {
return path;
}
// if nothing was found, return null
return null;
}

// now recursively search for the value
return _getPath(obj, []);
}

使用函数getPath,您可以执行以下操作:

var path = getPath(bigBox, "Batman");
console.log(path.join(" > ")); // logs "bigBox > mediumBoxB > smallBoxC > toyE"

如果所有变量都在一个对象中,您还可以使用附加上下文参数调用 getPath 函数,如下所示:

var path = getPath(context.bigBox, "Batman", context);



我对对象 bigBox 进行了一些更改,以便每个变量在对象中只出现一次。

这是 jsFiddle demo

关于javascript - 如何在嵌套数组中查找属性并返回其位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22798256/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com