面试题1:
const data = [
['2022/2/28', '雨'],
['2022/2/26', '晴'],
['2022/2/27', '阴'],
['2022/2/26', '运动'],
['2022/2/28', '工作']
];
转化成:
const resData = [{
time: '2022/2/26',
weather: '晴',
thing: '运动'
},{
time: '2022/2/27',
weather: '阴',
thing: '暂无'
},{
time: '2022/2/28',
weather: '雨',
thing: '工作'
}]
第一种写法
const thingList = ['运动', '工作'];
const weatherList = ['雨', '晴', '阴'];
const testObj = {};
const dataList = [];
data.forEach(([item, value]) => {
if (!testObj[item]) {
testObj[item] = {}
}
if (thingList.some((item) => item === value)) {
testObj[item].thing = value;
}
if (weatherList.some((item) => item === value)) {
testObj[item].weather = value;
}
})
for (var i in testObj) {
if(!('thing' in testObj[i])){
testObj[i].thing = '暂无';
}
if(!('weather' in testObj[i])){
testObj[i].weather = '暂无';
}
dataList.push({ item: i, ...testObj[i], })
}
console.log('dataList', dataList);
const data = [
['2022/2/28', '雨'],
['2022/2/26', '晴'],
['2022/2/27', '阴'],
['2022/2/26', '运动'],
['2022/2/28', '工作']
];
let resData = []
data.forEach(item => {
let obj= resData.find(res => {
if(res.time === item[0]){
return res
}
})
if(obj === undefined){
obj = {}
obj['time'] = item[0]
if (item[1].length === 1) {
obj['weather'] = item[1]
}else {
obj['thing'] = item[1]
}
resData.push(obj)
return
}else {
if (item[1].length === 1) {
obj['weather'] = item[1]
}else {
obj['thing'] = item[1]
}
}
})
resData.forEach(res => {
if(res.thing === undefined || res.thing === '' ) {
res['thing']= '暂无'
}
})
console.log('bingo==>',resData)
面试题2:
const data = [
{"CN": "cn"},
{"EN": "en"},
{"OK": "ok"}
]
转换成
const resData = [
{key: 'CN', value: 'cn'},
{key: 'EN', value: 'en'},
{key: 'OK', value: 'ok'}
]
使用reduce来进行操作
const aa = data.reduce((acc, cur) => {
var ob = {}
var c = JSON.stringify(cur).replaceAll('"','').replace('{', "").replace('}', "").split(":")
ob["key"] = c[0]
ob["value"] = c[1]
acc.push(ob)
return acc
}, []);
console.log(aa)