让我们有一个示例JS对象(又名"关联数组"):
var zoo = {
monkey: { legs: 4, color: "black" },
fish: { legs: 0, color: "yellow" },
turtle: { legs: 4, color: "green" },
emu: { legs: 2, color: "gray" },
};
现在我想要检索水生动物的嵌套对象(又名"子阵列")。是否有一个标准的JS / jQuery构造或函数来按数组过滤对象属性("用数组索引数组"),例如:
var aquatic = zoo["fish", "turtle"];
结果显然应该是{ { legs: 0, color: "yellow" }, { legs: 4, color: "green" } }
。
或for
循环是最简单的解决方案吗?
答案 0 :(得分:3)
您可以使用map()
并返回对象数组。
var zoo = {
monkey: { legs: 4, color: "black" },
fish: { legs: 0, color: "yellow" },
turtle: { legs: 4, color: "green" },
emu: { legs: 2, color: "gray" },
};
var aquatic = ["fish", "turtle"];
var result = aquatic.map(e => zoo[e]);
console.log(result)