最近学习Vue.js发现其为了实现对data内的数组和对象进行双向绑定,将数组和对象进行了封装。
如下的对象
todos: [
{
id: 1,
title: 'Do the dishes',
},
{
id: 2,
title: 'Take out the trash',
},
{
id: 3,
title: 'Mow the lawn'
}
]
会被封装成:
而封装后的这个对象传递到后台会出现无法识别的现象。
于是,我开始尝试将Vue.js封装后的对象进行封装。
var restore = function (vueObject) { var result = null; var type = Object.prototype.toString.call(vueObject); switch (type) { case '[object Array]': result = toArray(vueObject); break; case '[object Object]': result = toObject(vueObject); break; default: result = vueObject; break; } function toArray(vueArray) { var array = []; for (var index in vueArray) { var item = restore(vueArray[index]); array.push(item); } return array; } function toObject(vueObject) { var obj = new Object(); for (var index in vueObject) { var item = restore(vueObject[index]); obj[index] = item; } return obj; } return result; };
测试用例:
var json = { a: [ { a1: { a11: [1, 2, 3], a12: [1, 2, 3] }, a2: [{ a21: '21' }] }, { a3: { a31: [1, 2, 3], a32: [1, 2, 3] }, a4: [{ a41: '41' }] } ], b: { b1: 'b1', b2: 2 } };
Vue.js对象:
转换后的结果:
{"a":[{"a1":{"a11":[1,2,3],"a12":[1,2,3]},"a2":[{"a21":"21"}]},{"a3":{"a31":[1,2,3],"a32":[1,2,3]},"a4":[{"a41":"41"}]}],"b":{"b1":"b1","b2":2}}