(java题)筛选数组对象中某几个指定信息组成新数组放入原数组
- 问题记录
-
const arr1 = [ { nums0: 123, nums1: 25, nums2: 3, nums3: 3, storeId: "A007", storeName: "易购北辰店", targetType0: 1, targetType1: 0, targetType2: 6, targetType3: 2, workType: 1, }, { nums0: 123, nums1: 25, nums2: 3, nums3: 3, storeId: "A007", storeName: "易购南开店", targetType0: 1, targetType1: 0, targetType2: 6, targetType3: 2, workType: 1, }, ]; 目标结果: const arr1 = [ { storeId: "A007", storeName: "易购北辰店", workType: 1, List:[ {nums:123,targetType:1} {nums:25,targetType:0} {nums:3,targetType:6} {nums:3,targetType:2} ] }, { storeId: "A007", storeName: "易购南开店", workType: 1, List:[ {nums:123,targetType:1} {nums:25,targetType:0} {nums:3,targetType:6} {nums:3,targetType:2} ] }, ];
知识点:
includes() 方法用来判断一个数组是否包含一个指定的值,如果是返回 true,否则false。
向数组的末尾添加一个或多个元素,并返回新的长度。
console.dir(obj[, options])
用来对一个对象进行检查(inspect),并以易于阅读和打印的格式显示。
1 实现代码 2 arr1.map((v, i, arr) => { 3 console.log(`########## 第${i + 1}次遍历 ###########`); 4 let keys = Object.keys(v); //该方法返回一个数组,传入对象,返回属性名 5 let t = 0, //声明变量t 表示nums和targetType字段后的数字 6 list = []; //创建List数组,用来存放nums和targetType字段的信息 7 console.log(v); 8 console.log("v@@@@@@@@@@", v); 9 console.log("i", i); 10 console.log("arr", arr); 11 console.log("keys", keys); 12 keys.map((k, j) => { 13 //此处k对应每一个字段如:nums0,nums2.。。 14 console.log("k----------", k); 15 if (k.includes("nums")) { 16 // list.push({nums:v[keys[j]],targetType:v['targetType'+t]}) //方法一 17 list.push({ nums: v["nums" + t], targetType: v["targetType" + t] }); //方法二 18 t++; 19 } 20 }); 21 v.yangyang = list; 22 // delete v.nums0; 23 // delete v.targetType0; 24 }); 25 console.dir(arr1, { depth: 3 });
打印截图