根据索引数组从对象中获取特定的javascript值 [英] Pluck specific javascript value from an object based on an array of indexes

查看:735
本文介绍了根据索引数组从对象中获取特定的javascript值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个这样的嵌套对象:

Given a nested object like this:

var cars = {
    "bentley": {
        "suppliers": [
            {
            "location": "England",
            "name": "Sheffield Mines"}
        ]
        // ...
    }
};

和这样的数组 [bentley,供应商, 0,name] ,是否有现有的功能可以采摘最深的元素,即 pluck_innards(汽车,['bentley',供应商,0 ,名称])并返回谢菲尔德矿山。

and an array like this ["bentley", "suppliers", "0", "name"], is there an existing function that will pluck the deepest element, i.e. pluck_innards(cars, ['bentley', "suppliers", "0", "name"]) and that returns "Sheffield Mines".

换句话说,是否有一个函数(我将其命名为 deep_pluck )其中

In other words, is there a function (which I will name deep_pluck) where

deep_pluck(cars, ['bentley', 'suppliers', '0', 'name']) 
         === cars['bentley']['suppliers']['0']['name']

在我看来,这很简单,但很常见,可能是在一个Javascript实用程序库中完成的,例如jQuery lo-dash /下划线 - 但我还没有看到它。

It seems to me that this is simple, yet common enough, to have probably been done in one of the Javascript utility libraries such as jQuery or lo-dash/underscore - but I have not seen it.

我的想法是微不足道的,包括:

My thought is something trivial, along the lines of:

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];
}

我发布了在jsFiddle上

当然,如果函数足够聪明以确定何时需要数组中的数字索引,那将会很有帮助。我不确定其他注意事项可能会引起关注。

It would be helpful of course if the function were smart enough to identify when numerical indexes in arrays are needed. I am not sure offhand what other caveats may be a concern.

对于我认为已经巧妙解决的问题,这是一个相当长的问题,但我想发布这是因为我有兴趣看看有什么解决方案。

This is all a fairly long question for something I imagine has already been cleverly solved, but I thought to post this as I would interested in seeing what solutions are out there.

推荐答案

我认为你不会遇到阵列问题索引,如果你将它们作为数字 0 传递。

I don't think you'll have problems with Array indexes if you pass them as number 0.

这是你的函数的替代版本,没有递归:

Here's alternative version of your function without recursion:

function deep_pluck(object, identities) {
    var result = object;
    for(var i = 0; i < identities.length; i++) {
        result = result[identities[i]];
    }
    return result;
}

这里的工作示例: http://jsfiddle.net/AmH2w/1/

这篇关于根据索引数组从对象中获取特定的javascript值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆