这是开始的代码;
data = {
"questions": ["Who", "Where", "How"],
"names": ["Bill", "Fred", "Lindsey"],
"cities": ["Baltimore", "New York", "Chicago"],
"values": [
[
[50, 20, 40],
[40, 90, 10],
[50, 75, 30]
],
[
[33, 57, 100],
[20, 70, 89],
[16, 40, 68]
],
[
[3, 26, 54],
[62, 69, 86],
[23, 81, 98]
]
]
}
function sortObject() {
var values;
var question = data.questions.indexOf("Who", "Where")
var name = data.names.indexOf("Bill");
var city = data.cities.indexOf("Baltimore");
values = data.values[question][name][city]
console.log(values)
}
sortObject()
我希望能够返回“Who”和“Where”的结果,同时排除“How”。
所以最终结果将是 [50, 33]。
我还希望该方法能够处理无限数量的项目,例如“问题”数组中可能有 100 个项目,我将能够单独选择我想展示的项目无论它们在数组中的位置如何。
我认为我将不得不遍历每个项目,然后可能按照以下方式做一些事情;
for (var question = 0; question < data.questions.length; question++) {
if (data.questions.indexOf() == "Who" || "Where") {
var name = data.names.indexOf("Bill");
var city = data.cities.indexOf("Baltimore");
values = data.values[question][name][city]
console.log(values)
}
}
但这行不通,所以我不确定从这里到哪里去?
希望一切都清楚,如果您需要更多信息,请告诉我;
在此先感谢您的帮助/建议!
最佳答案
如果要搜索的项目不止一项,您可以遍历。
function getData(question, name, city) {
var result = [];
(Array.isArray(question) ? question : [question]).forEach(function (q) {
var r = data.values[data.questions.indexOf(q)] || [];
(Array.isArray(name) ? name : [name]).forEach(function (n) {
var rr = r[data.names.indexOf(n)] || [];
(Array.isArray(city) ? city : [city]).forEach(function (c) {
result.push({
question: [q, n, c],
value: rr[data.cities.indexOf(c)]
});
});
});
});
return result;
}
var data = { "questions": ["Who", "Where", "How"], "names": ["Bill", "Fred", "Lindsey"], "cities": ["Baltimore", "New York", "Chicago"], "values": [[[50, 20, 40], [40, 90, 10], [50, 75, 30]], [[33, 57, 100], [20, 70, 89], [16, 40, 68]], [[3, 26, 54], [62, 69, 86], [23, 81, 98]]] },
result = getData(["Who", "Where"], "Bill", "Baltimore");
console.log(result);
另一个更动态的解决方案可能是使用搜索对象的迭代递归方法。
function getData(search) {
var result = [],
order = ['questions', 'names', 'cities'];
function iter(value, level) {
if (level === order.length) {
return result.push(value);
}
search[order[level]].forEach(function (a) {
iter((value || [])[data[order[level]].indexOf(a)], level + 1);
});
}
iter(data.values, 0);
return result;
}
var data = { "questions": ["Who", "Where", "How"], "names": ["Bill", "Fred", "Lindsey"], "cities": ["Baltimore", "New York", "Chicago"], "values": [[[50, 20, 40], [40, 90, 10], [50, 75, 30]], [[33, 57, 100], [20, 70, 89], [16, 40, 68]], [[3, 26, 54], [62, 69, 86], [23, 81, 98]]] },
result = getData({ questions: ["Who", "Where"], names: ["Bill"], cities: ["Baltimore"] });
console.log(result);
关于javascript - 如何返回javascript多维数组中多个索引的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38141448/