对象属性过多,如何便捷获取对象中多个属性的值??

DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Documenttitle>
head>
<body>
  <script>
    // https://segmentfault.com/q/1010000012715651


    const obj = {
      a: '1',
      b: '2',
      c: '3',
      d: '4'
    }

    const arr = ['a', 'd']
    const aaaa = handleFilterObjectProperties(obj, arr)
    console.log('%c%s', 'color:#cb3a56', 'Log: aaaa--行', aaaa)
    
    /**
     * @description: 过滤对象属性,遍历数组,返回对象中跟数组相匹配的项
     * @param {Object} obj
     * @param {Array} arr 跟obj匹配,获取obj中的值 arr = ['a']; obj = {a: '1'}; obj[arr[0]];
     * @return {Object} {a: '1'}
     */
    function handleFilterObjectProperties(obj, arr) {
      if (isObject(obj) && Z_IsNotEmtArray(arr)) {
        return arr.reduce((accumulator, key) => {
          if (key in obj) {
            accumulator[key] = obj[key]
            return accumulator
          }
        }, {});
      }
      return {}
    }

    function isObject(obj) {
      return obj !== null && typeof obj === 'object'
    }

    function Z_IsNotEmtArray(o) {
      return Z_IsArray(o) && typeof(o.length) && o.length > 0
    }

    function Z_IsArray(o) {
      return o && (o instanceof Array) || o.constructor === Array
    }

  script>
body>
html>

你可能感兴趣的:(javascript,前端,vue.js)