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");
有没有办法将String Dot Notation “interests.color”转换为对象“n [field]”来更新值?
从其他帖子得到答案。
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);
}
}
答案 0 :(得分:2)
你在这里没有处理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>