如何展平对象文字属性? [英] How flatten object literal properties?
本文介绍了如何展平对象文字属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个由旧服务器返回的对象,我想通过JavaScript,jQuery甚至Underscore.js在客户端更改结构.
I have an object being returned by a legacy server and I want to change the structure on the client-side via JavaScript, jQuery, or even Underscore.js.
下面是我的原始对象的样子:
Below is what my original object looks like:
[
{
"Id":{
"LValue":1,
"Value":1
},
"Date":{
"LValue":"2013-10-17T00:00:00",
"Value":"2013-10-24T00:00:00"
},
"User":{
"LValue":508,
"Value":507
},
"Comments":{
"LValue":"This a test load",
"Value":"This a test"
},
"Name":"John Doe",
"IsDeleted":false
}
]
不过,在客户端,我想将其展平以获取值",并将"LValues"填充到单独的属性中,以便以后不再需要时不要松开它们:
On the client-side though, I would like to flatten it to get the "Values" and stuff the "LValues" into a separate property so I don't loose them if I need it later:
[
{
"Id":1,
"Date":"2013-10-24T00:00:00",
"User":507,
"Comments":"This a test",
"Name":"John Doe",
"IsDeleted":false,
"LValues": {
"Id":1,
"Date":"2013-10-17T00:00:00",
"User":508,
"Comments":"This a test load"
}
}
]
这将使使用该对象变得非常容易,任何帮助将深表感谢!
this would make working with the object so much easier and any help would be deeply appreciated!
推荐答案
var oList = [
{
"Id":{
"LValue":1,
"Value":1
},
"Date":{
"LValue":"2013-10-17T00:00:00",
"Value":"2013-10-24T00:00:00"
},
"User":{
"LValue":508,
"Value":507
},
"Comments":{
"LValue":"This a test load",
"Value":"This a test"
},
"Name":"John Doe",
"IsDeleted":false
}
];
var newFormat = _(oList).map(function(o) {
var flattened = { LValues: {} };
_(o).each(function(val, propName) {
flattened[propName] = val.Value ? val.Value : val;
if(val.LValue) {
flattened.LValues[propName] = val.LValue;
}
});
return flattened;
}
这篇关于如何展平对象文字属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文