一、将 [ { 1: 1, 2: 2, 3: 3 }, { 1: 4, 2: 5, 3: 6 },{ 1: 7, 2: 8, 3: 9 }];转换为 { 1: [1,4,7] , 2:[2,5,8 ], 3:[3,6,9] }
fn1() {
let arr = [
{ 1: 1, 2: 2, 3: 3 }, { 1: 4, 2: 5, 3: 6 },{ 1: 7, 2: 8, 3: 9 }
];
let newarr = {};
arr.forEach((item) => {
for (let key in item) {
let value = newarr[key];
if (value) {
value.push(item[key]);
} else {
newarr[key] = [item[key]];
}
}
});
console.log(newarr); // {1: [1,4,7] , 2:[2,5,8 ], 3:[3,6,9] }
}
二、['john-reese', 'harold-finch', 'sameen-shaw'] 转换成 [{name: 'John Reese'}, {name: 'Harold Finch'}, {name: 'Sameen Shaw'}]
fn2() {
let arr = ["john-reese", "harold-finch", "sameen-shaw"];
let objArray = arr.map((item) => {
item = item.replace("-", " ");
let a = item[0];
let b = a.toUpperCase();
item = item.replace(a, b);
return { name: item };
});
console.log(objArray);
}