给定一个这样的嵌套对象:
var cars = {
"bentley": {
"suppliers": [
{
"location": "England",
"name": "Sheffield Mines"}
]
// ...
}
};
Run Code Online (Sandbox Code Playgroud)
像这样的数组["bentley", "suppliers", "0", "name"],是否有一个现有的函数将采取最深的元素,即pluck_innards(cars, ['bentley', "suppliers", "0", "name"])返回"谢菲尔德矿".
换句话说,是否有一个功能(我将其命名deep_pluck)在哪里
deep_pluck(cars, ['bentley', 'suppliers', '0', 'name'])
=== cars['bentley']['suppliers']['0']['name']
Run Code Online (Sandbox Code Playgroud)
在我看来,这很简单,但很常见,可能已经在一个Javascript实用程序库中完成,例如jQuery或lo-dash/underscore - 但我还没有看到它.
我的想法是微不足道的,包括:
function deep_pluck(array, identities) {
var this_id = identities.shift();
if (identities.length > 0) {
return deep_pluck(array[this_id], identities);
}
return array[this_id];
}
Run Code Online (Sandbox Code Playgroud)
我在jsFiddle上发布的内容.
当然,如果函数足够智能以确定何时需要数组中的数字索引,那将是有帮助的.我不确定其他警告可能会引起关注.
对于我想象已经巧妙解决的问题,这是一个相当长的问题,但我想发布这个,因为我有兴趣看看那里有什么解决方案.