根据动态键列表设置嵌套数组元素的值?

时间:2015-04-28 18:28:38

标签: javascript arrays recursion javascript-objects

我有一个像这样动态生成的对象(我只是在这里注意'children'数组键用于显示目的,假设它是一个语法上合理的声音数组):

foo: {
    children: [
        0: {
            children: [
               3: { 
                   children: [
                       6: {
                           //...etc

然后我有一个生成的密钥列表:

var keys = [0,3,6];

我需要设置键列表所描述的数组元素的值,如下所示:

foo.children[0].children[3].children[6] = "bar";

有什么想法吗?我尝试了一些不同的递归技术,但我在某处遗漏了一些东西。

3 个答案:

答案 0 :(得分:0)

虽然你可以递归地执行此操作,但我认为在这样的循环中执行此操作会更有效:

function setNestedChild( obj, path, value ){
    var child = obj;
    path.forEach(function( i, idx ){
        if( idx == path.length - 1 ){
            child.children[ i ] = value;
        }
        else {
            child = child.children[ i ];
        }
    });
}

答案 1 :(得分:0)

的方法怎么样?
#import "MyCardCellTableViewCell.h"

//managers
#import "FFFColorManager.h"

@implementation MyCardCellTableViewCell

- (void)awakeFromNib {
    [self initializeAppearance];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
}

#pragma mark - Private

- (void)initializeAppearance {
    [self initializeFonts];
    [self initializeColors];
}

- (void)initializeFonts {
    self.title.font = [UIFont fontWithName:@"Roboto-Regular" size:14.0];
    self.subtitle.font = [UIFont fontWithName:@"Roboto-Regular" size:12.0];
    self.username.font = [UIFont fontWithName:@"Roboto-Light" size:10.0];
}

- (void)initializeColors {
    self.respondLabel.backgroundColor = [[FFFColorManager sharedManager] colorForApplicationColorIdentifier:ApplicationColorIdentifierQuestionCardSectionRespondBackground];
    self.containerView.backgroundColor = [[FFFColorManager sharedManager] colorForApplicationColorIdentifier:ApplicationColorIdentifierTableViewBackground];

    UIColor *cardForegroundColor = [[FFFColorManager sharedManager] colorForApplicationColorIdentifier:ApplicationColorIdentifierQuestionCard];
    self.title.backgroundColor = cardForegroundColor;
    self.subtitle.backgroundColor = cardForegroundColor;
}

@end
  • 此函数仅用于检索所需的元素,实际上并未设置该值。

答案 2 :(得分:0)

这个怎么样?

function setVal(obj, keys, val){
    var temp = obj;
    while(keys.length){
        var i = keys.pop();
        if(!keys.length) return temp.children[i] = val;
        temp = temp.children[i];
    }   
}