js数据操作笔记整理

// 模拟后台接口
https://designer.mocky.io

// 日期格式化
Date.prototype.toFormattedString = function (format) {
    const O = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "H+": this.getHours(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "f": this.getMilliseconds()
    };
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (let k in O) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, (RegExp.$1.length === 1) ? (O[k]) : (("00" + O[k]).substr(("" + O[k]).length)));
        }
    }
    return format;
}

let date = new Date();

date.toFormattedString('yyyy-MM-dd HH:mm:ss'); // 2019-11-07 08:52:13
date.toFormattedString('yy/MM/dd'); // 19/01/01
date.toFormattedString('M月d日'); // 11月7日
date.toFormattedString('HH:mm:ss'); // 08:52:13
date.toFormattedString('m分,s秒'); // 52分,13秒

// 深拷贝
function deepClone(obj) {
    let newObj = Array.isArray(obj) ? [] : {}
    if (obj && typeof obj === "object") {
        for (let key in obj) {
            if (obj.hasOwnProperty(key)) {
                newObj[key] = (obj && typeof obj[key] === 'object') ? deepClone(obj[key]) : obj[key];
            }
        }
    } 
    return newObj
}

// 取对象属性值
let obj = {
    school: {
      class1: {
        student: 50
      }
    }
}

function safeProps(func, defaultVal) {
    try {
        return func();
    } catch (e) {
        return defaultVal;
    }
}

safeProps(function(){
    student = obj.school.class1.student
}, -1)
// 现在有这样的两个数组
key: ['key0', 'key1'];
value: ['value0', 'value1'];

// 希望转换成以下格式
[{key0: 'value0'}, {key1: 'value1'}]

Object.fromEntries(key.map((k, i) => [k, value[i]]))
// 获取动态key的值
'form.input'.split('.').reduce((prev, cur) => prev[cur], {
    form: {
        input: 1
    }
})

result: 1
// 生成一个从140到220的数组
[...Array(221).keys()].slice(140)
// 随机增长
function * random() {
  let start = 10000
  while (1) {
    start += new Date().getTime() % 1000
    yield start
  }
}

result: random().next()
// 给对象值添加"引号"
const result = '[{"id":1234567890},{"id":1234567891}]'.replace(/(?<="id"\s*:\s*)(\d+)/g, '"$1"')

result: [{"id": "1234567890" },{"id": "1234567891" }]
// 判断属性值是否存在
let x = a?.e?.f		// 兼容性不够

// 等效于
let x = (a !== null && a !== undefined) && (a.e !== null && a.e !== undefined) && a.e.f;
// 数组转对象
const type = [
    { num: "A", content: "I'm A." },
    { num: "B", content: "I'm B." },
    { num: "C", content: "I'm C." }
]
const target = {}
type.forEach(i => target[ "choice" + i.num ] = i.content)
result: console.log(target)
// 过滤数据
const treeData = [{
  title: "1",
  key: "1",
  children: [{
    title: "1-1",
    key: "1-1",
    children:[{
      title:"1-1-1",
      key:"1-1-1",
    },{
      title:"1-1-2",
      key:"1-1-2",
    }]
  }, {
    title: "1-2",
    key: "1-2",
  },{
    title: "1-3",
    key: "1-3",
  },{
    title: "1-4",
    key: "1-4",
  }],
}];

function f(arr, selectedKey) {
  return arr.filter(item => item.key !== selectedKey).map(item => {
    item = Object.assign({}, item)
    if (item.children) {
      item.children = f(item.children, selectedKey)
    }
    return item
  })
}

result: f(treeData, '1-2')

// 如何根据 ['北京市','北京市','东城区']
// 查出对应的code ["110000", "110100", "110101"]
const data = {
      'value': '110000',
      'label': '北京市',
      'children': [
        {
          'value': '110100',
          'label': '北京市',
          'children': [
            {
              'value': '110101',
              'label': '东城区'
            }
           ]
        }
      ]
 }
function findCodeByName(data, nameList) {
    if(nameList.length === 0) return [];
    const [name, ...rest] = nameList;
    const item = data.find(i => i.label === name);
    if(!item) throw new Error(name + ' cannot be found in the list!');
    return [item.value, ...findCodeByName(item.children, rest)];
}

result: findCodeByName(data, ['天津市','天津市', '和平区'])
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值