This question already has answers here:
How to set object property (of object property of..) given its string name in JavaScript?
                                
                                    (13个回答)
                                
                        
                                2年前关闭。
            
                    
function filterResult(field, value){
    var result = [
        {
            "name": "Johnson",
            "age": "12",
            "interests": {
                "color": "red"
            }
        },
        {
            "name": "Calvin",
            "age": "24",
            "interests": {
                "color": "blue"
            }
        }
    ];
    var filter = $.map(result, function(n, i){
        //other stuff here...
        n[field] = value; //dot notation
        return n;
    });
    return filter;
}

filterResult("interests.color","black");


有没有一种方法可以将字符串点表示法“ interests.color”转换为对象“ n [field]”以更新值?


请注意“ interests.color”只是一个例子。有时水平可能会更高一些“ interests.car.make.year”。动态是一个主意。


得到了其他帖子的答案。

function setterDotNotation(obj, str, value){
    if (typeof str == 'string'){
        return setterDotNotation(obj,str.split('.'), value);
    }else if (str.length==1 && value!==undefined){
        return obj[str[0]] = value;
    }else if (str.length==0){
        return obj;
    }else{
        return setterDotNotation(obj[str[0]], str.slice(1), value);
    }
}

最佳答案

您在这里不是在处理JSON,而是在处理一个对象(更具体地说,是一个对象数组)。

无论如何,您可以在.split()"interests.color" "."字符串,然后使用两个部分:

var fieldNames = field.split(".");       // returns ["interests", "color"]
n[fieldNames[0]][fieldNames[1]] = value;


展开并运行以下代码片段,以查看它在上下文中是否有效:



function filterResult(field, value){
    var result = [
        {
            "name": "Johnson",
            "age": "12",
            "interests": {
                "color": "red"
            }
        },
        {
            "name": "Calvin",
            "age": "24",
            "interests": {
                "color": "blue"
            }
        }
    ];
    var filter = $.map(result, function(n, i){
        //other stuff here...
            var fieldNames = field.split(".");
            n[fieldNames[0]][fieldNames[1]] = value;
            return n;
    });
    return filter;
}

console.log( filterResult("interests.color","black") );

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

09-10 16:31