我有一个像这样的对象......
"data": {
"1": {
"id": 32,
"name": "E",
"link": "",
},
"2": {
"id": 33,
"name": "EC",
"link": "",
},
}
如何使用上面的变量设置每个“链接”值?例如,我想做一些像
这样的事情"data": {
"1": {
"id": 32,
"name": "E",
"link": "id="+this.id+" and name="+this.name,
},
"2": {
"id": 33,
"name": "EC",
"link": "id="+this.id+" and name="+this.name,
},
使对象成为这样......
"data": {
"1": {
"id": 32,
"name": "E",
"link": "id=32 and name=E",
},
"2": {
"id": 33,
"name": "EC",
"link": "id=33 and name=EC",
},
答案 0 :(得分:1)
我建议迭代属性并更改所需的项目。
var object = { data: { "1": { "id": 32, "name": "E", "link": "", }, "2": { "id": 33, "name": "EC", "link": "", } } };
Object.keys(object.data).forEach(function (k) {
object.data[k].link = 'id=' + object.data[k].id + ' and name=' + object.data[k].name;
});
document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');
答案 1 :(得分:0)
我通常会把它变成一个功能:
"data": {
"1": {
"id": 32,
"name": "E",
"get_link": function() { return "id="+this.id+" and name="+this.name }
}
}
然后您可以像whatever.get_link()
答案 2 :(得分:0)
有两种方法可以解决这个问题。
您可以创建后处理器来处理占位符值。我制作了一个通用的预处理器,它应该动态搜索所有字符串属性的占位符。
var linkStore = {
"data": {
"1": {
"id": 32,
"name": "E",
"link": "id={{id}} and name={{name}}"
},
"2": {
"id": 33,
"name": "EC",
"link": "id={{id}} and name={{name}}"
}
}
};
function postProcess(data, root) {
var records = root != null ? data[root] : data;
Object.keys(records).forEach(function(recordId) {
var record = records[recordId];
Object.keys(record).forEach(function(property) {
if (typeof record[property] === 'string') {
record[property] = record[property].replace(/{{(\w+)}}/g, function(match, value) {
return record[value];
});
}
});
});
return data;
}
var result = postProcess(linkStore, 'data');
document.body.innerHTML = '<pre>' + JSON.stringify(result, null, 2) + '</pre>';
&#13;
或者,如果您不想修改原始数据。您可以添加要应用于每个记录的属性映射。
var linkStore = {
"data": {
"1": {
"id": 32,
"name": "E",
"link": ""
},
"2": {
"id": 33,
"name": "EC",
"link": ""
}
}
};
function postProcess(data, root, propertyMap) {
var records = root != null ? data[root] : data;
Object.keys(records).forEach(function(recordId) {
var record = records[recordId];
Object.keys(propertyMap).forEach(function(property) {
record[property] = propertyMap[property].call(record, record[property]);
});
});
return data;
}
var result = postProcess(linkStore, 'data', {
link : function(oldValue) {
return 'id=' + this.id + ' and name=' + this.name
}
});
document.body.innerHTML = '<pre>' + JSON.stringify(result, null, 2) + '</pre>';
&#13;