1、后端数据处理
从某数据库接口得到如下值:
{
rows: [
["Lisa", 16, "Female", "2000-12-01"],
["Bob", 22, "Male", "1996-01-21"]
],
metaData: [
{ name: "name", note: '' },
{ name: "age", note: '' },
{ name: "gender", note: '' },
{ name: "birthday", note: '' }
]
}
rows
是数据,metaData
是对数据的说明。现写一个函数 parseData
,将上面的对象转化为期望的数组:
[
{ name: "Lisa", age: 16, gender: "Female", birthday: "2000-12-01" },
{ name: "Bob", age: 22, gender: "Male", birthday: "1996-01-21" },
]
方法一:
const parseData = (data) => {
let array = [];
let obj = {}
data.rows.forEach(r => {
obj = {};
data.metaData.forEach((item,i) => {
obj[item.name] = r[i];
})
array.push(obj);
})
return array;
}
console.log(parseData(obj));
方法二:
const parseData2 = (data) => {
return data.rows.map(r => {
return r.reduce((res,cur,i) =>{
res[data.metaData[i].name]=cur;
return res;
}, {} );
})
}
console.log( parseData2(obj));
2、字符串居中补全
完成函数 centerPad
可以让一个字符串居中包裹在指定的可重复填充的字符串中间,例如:
centerPad('Hello', 13, 'abc') // => 'abcaHelloabca'
centerPad('Gook Luck!', 30, '*~') // => '*~*~*~*~*~Gook Luck!*~*~*~*~*~'
第一个参数为被包裹字符串,第二个参数为最终的字符串长度,第三个参数为用来填充的字符。
如果字符串无法完全居中,那么让字符串偏左,例如:
centerPad('Hello', 10, 'abc') // => 'abHelloabc'
如果第二个参数传入的字符串长度比原来长度要短,直接返回原有字符串即可,例如:
centerPad('Hello', 1, 'abc') // => 'Hello'
方法:
const centerPad = (str, len, pad) => {
let L = Math.floor((len-str.length)/2);
return ''.padStart(L,pad) + str + ''.padEnd(len - L - str.length,pad);
}
console.log(centerPad('Hello', 3, 'abc') )
3、数组去重
编写一个函数 unique(arr)
,返回一个去除数组内重复的元素的数组。例如:
unique([0, 1, 2, 2, 3, 3, 4]) // => [0, 1, 2, 3, 4]
unique([0, 1, '1', '1', 2]) // => [0, 1, '1', 2]
方法:
const unique = (arr) => [...new Set(arr)];//或者Array.from(new Set(arr))
console.log(unique([0, 1, '1', '1', 2]) )