这种怎么转,按照arr1 中detail个数 分成多个组 最终转成arr2 这种

var arr = [

{

name:"张三",

value:111,

totalfee: 60,

detail:[

{

cost: 25,

endtime: "2021-10-11",

reason: "测试1"

},

{

cost: 35,

endtime: "2021-10-22",

reason: "测试2"

},

]

},

{

name:"李四",

value:222,

totalfee: 150,

detail:[

{

cost: 10,

endtime: "2021-10-11",

reason: "测试1"

},

{

cost: 20,

endtime: "2021-10-12",

reason: "测试2"

},

{

cost: 50,

endtime: "2021-10-13",

reason: "测试4"

},

{

cost: 70,

endtime: "2021-10-14",

reason: "测试3"

},

]

},

];

转成

var arr2 = [

{

name:"张三",

value:111,

totalfee: 60,

cost: 25,

endtime: "2021-10-11",

reason: "测试1"

},

{

name:"张三",

value:111,

totalfee: 60,

cost: 35,

endtime: "2021-10-22",

reason: "测试2"

},

{

name:"李四",

value:222,

totalfee: 150,

cost: 10,

endtime: "2021-10-11",

reason: "测试1"

},

{

name:"李四",

value:222,

totalfee: 150,

cost: 20,

endtime: "2021-10-12",

reason: "测试2"

},

{

name:"李四",

value:222,

totalfee: 150,

cost: 50,

endtime: "2021-10-13",

reason: "测试4"

},

{

name:"李四",

value:222,

totalfee: 150,

cost: 70,

endtime: "2021-10-14",

reason: "测试3"

},

];


回答:

这种怎么转,按照arr1 中detail个数 分成多个组 最终转成arr2 这种

arr.flatMap(({detail,...item})=>{

return detail.map(detailItem=>{

return Object.assign({},item,detailItem);

})

})

es5
这种怎么转,按照arr1 中detail个数 分成多个组 最终转成arr2 这种

arr.flatMap(function(item){

var detail = item.detail;

delete item.detail;

return detail.map(function(detailItem){

return Object.assign({},item,detailItem);

})

})

ie可运行
这种怎么转,按照arr1 中detail个数 分成多个组 最终转成arr2 这种

arr.reduce(function(acc, item){

var detail = item.detail;

delete item.detail;

return acc.concat(detail.map(function(detailItem){

var obj={};

for(prop in item){

obj[prop] = item[prop];

}

for(prop in detailItem){

obj[prop] = detailItem[prop];

}

return obj;

}))

},[])

arr.reduce(function(acc, item){

var detail = item.detail;

delete item.detail;

detail.forEach(function(detailItem){

var obj={};

for(prop in item){

obj[prop] = item[prop];

}

for(prop in detailItem){

obj[prop] = detailItem[prop];

}

acc.push(obj);

})

return acc;

},[])

也可以用 babel babeljs 打补丁的方式,支持es6
这种怎么转,按照arr1 中detail个数 分成多个组 最终转成arr2 这种
https://www.babeljs.cn/repl


回答:

这个问题其实没那么复杂,你看下原数组有几个元素?2个;detail有几个?一共有6个,而你要的结果数组刚好就是6个元素,detail又是数组元素中某个属性的数组,所以要写双重循环,第一重循环两次,第二重一共循环6次,把内外属性值合并到一起放入空数组就行了。用各种数组方法实现也行,但不太利于理解逻辑,用最原始的写法实现如下:

function transform(arr) {

var ret = [];

for (var i = 0; i < arr.length; ++i) {

var item = arr[i];

var name = item.name;

var value = item.value;

var totalfee = item.totalfee;

var detail = item.detail;

for (var j = 0; j < detail.length; ++j) {

item = detail[j];

var obj = {

name: name,

value: value,

totalfee: totalfee,

cost: item.cost,

endtime: item.endtime,

reason: item.reason

};

ret.push(obj);

}

}

return ret;

}

console.dir(transform(arr));

以上是 这种怎么转,按照arr1 中detail个数 分成多个组 最终转成arr2 这种 的全部内容, 来源链接: utcz.com/p/936527.html

回到顶部