在所有JSON对象的键之前添加名称空间 [英] Prepending namespace to all of a JSON object's Keys
问题描述
我不太了解JavaScript,但这是我要做的事情的摘要.
I'm not overly knowledgeable in JavaScript, but here's the rundown on what I'm trying to do.
我有一个由外部源准备的JSON对象.我按原样使用该Object字符串连接到我准备的另一个JSON对象,但是问题是每个键都必须在它们前面有一个名称空间缩写.
I have a JSON object that is prepared by an external source. I'm using that Object as-is to string on to another JSON object that I have prepared, but the problem is that each of the keys need to have a namespace abbreviation in front of them.
这就是我所拥有的:
obj1 = {
"key1": "value",
"key2": "value",
"key3": "value",
"key4": {
"subkey1": "value",
"subkey2": "value"
}
}
我希望它变成什么:
obj1 = {
"ns:key1": "value",
"ns:key2": "value",
"ns:key3": "value",
"ns:key4": {
"ns:subkey1": "value",
"ns:subkey2": "value"
}
}
这应该动态完成,因为这将用于同一项目的多个不同方面.因此,我希望简单地使用一个函数,将"obj1"传递给它,并使其吐出转换后的JSON对象,无论我给它什么.
This should be done dynamically, since this will be used for several different aspects of the same project. So I'm hoping to simply have a function that I pass 'obj1' into and have it spit out the converted JSON Object, no matter what I give it.
最简单的方法是什么?同样,我不习惯JavaScript,因此欢迎您举一些例子.
What would the easiest way to go about this be? Again, I'm not used to JavaScript, so examples are welcome.
PS.CoffeeScript解决方案也是可以接受的.我基本上是用JS编写出来的,然后使用js2coffee.org进行转换.
PS. A CoffeeScript solution is also acceptable. I'm basically writing it out in JS then converting this using js2coffee.org.
推荐答案
尝试检查代码以查看是否错过了任何未处理的案例.我想您必须先检查一些事情,然后再使用它...
Try to check the code to see if I missed any unhandled cases. You have to check for a few things before you use it I guess...
var obj1 = {
"key1": "value",
"key2": "value",
"key3": "value",
"key4": {
"subkey1": "value",
"subkey2": "value"
}
};
var rename = function(obj, prefix){
if(typeof obj !== 'object' || !obj){
return false; // check the obj argument somehow
}
var keys = Object.keys(obj),
keysLen = keys.length,
prefix = prefix || '';
for(var i=0; i<keysLen ;i++){
obj[prefix+keys[i]] = obj[keys[i]];
if(typeof obj[keys[i]]=== 'object'){
rename(obj[prefix+keys[i]],prefix);
}
delete obj[keys[i]];
}
return obj;
};
这篇关于在所有JSON对象的键之前添加名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!