我有一个
JavaScript数组:
var data = [{abc: "vf",def: [{ a:"1", b:"3"},{a:"2",b:"4"}]}];
我希望它转换为:
[{"abc":"vf","a":"1","b":"3"},{"abc":"vf","a":"2","b":"4"}]
我已经为它编写了JavaScript代码:
使用Javascript:
var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);
Object.defineProperty(Array.prototype, "pushArrayMembers", {
value: function() {
for (var i = 0; i < arguments.length; i++) {
var to_add = arguments[i];
for (var n = 0; n < to_add.length; n+=300) {
push_apply(this, slice_call(to_add, n, n+300));
}
}
}
});
var globalResultArr = [];
var data = [{abc: "vf",def: [{ a:"1", b:"3"},{a:"2",b:"4"}]}];
function f(){
for(var i=0;i<data.length;i++){ //Iterate Data Array
var obj = data[i];
var resultArray = [{}];
for (var key in obj) { // Iterate Object in Data Array
if (obj.hasOwnProperty(key)) {
if(Object.prototype.toString.call(obj[key]) === "[object Array]"){
var tempRes = $.extend(true, [], resultArray);
resultArray = [];
for(var k=0;k<tempRes.length;k++){
var tempResObj = tempRes[k];
for(var j=0;j<obj[key].length;j++){ // If it has array, then iterate it as well
var innerObj = obj[key][j]; //Iterate Object in inner array
for(var innerkey in innerObj){
if (innerObj.hasOwnProperty(innerkey)) {
tempResObj[innerkey] = innerObj[innerkey];
}
}
resultArray.push(tempResObj);
}
}
}else{
for(var i=0;i<resultArray.length;i++){
resultArray[i][key] = obj[key];
}
}
}
}
globalResultArr.pushArrayMembers(resultArray);
}
document.getElementById("test").innerHTML = JSON.stringify(globalResultArr);
}
f();
HTML:
<div id="test"></div>
问题是当数据数组中的项>时浏览器崩溃10000.我怎样才能做到这一点?有没有更简单的方法?
最佳答案 这是一次尝试.它假设每个对象中只有一个属性是数组.它们用剩余的属性组成一个对象,并使用数组属性中的每个值创建一个新的克隆.
*现在按要求工作*
var resultArray = [],
len = data.length,
tempObj,
newObj,
targetVal,
targetKey,
composeObj,
tempJson,
key,
i, k;
for(i = 0; i < len; i++) {
tempObj = data[i];
// obj to build up
composeObj = {};
// look at all key/vals in obj in data
for(key in tempObj) {
keyObj = tempObj[key];
// is it an array?
if(Array.isArray(keyObj)) {
// save key/val for array property
targetVal = keyObj;
targetKey = key;
}
else {
// copy non-array properties to empty object
composeObj[key] = keyObj;
}
}
// json-ify the object for cloning
tempJson = JSON.stringify(composeObj);
// compose new object for each val in array property
targetVal.map(function(val) {
// clone object
newObj = JSON.parse(tempJson);
// add array values as object properties
for(k in val) {
newObj[k] = val[k];
}
// add to results
resultArray.push(newObj);
});
}