如何使用自定义函数动态获取对象 属性

How to get object property dynamically using a custom function

我有一个接受 属性 名称的函数

func(propertyName) {
  return object[propertyName];
}

所以通过调用 func('value') 将 return object.value

但是对象很复杂,所以它有内部道具

我想做的就是能够做到这一点func('property1.property2')

最好的方法是什么?

试试这个:

示例数据: a={b:{c:"hellooo"}};

功能: function getValue(object,propertyName){ return propertyName.split(".").reduce((a,c)=>a[c],object); }

回复:

getValue(a,"b.c") = hellooo

reduce and the Optional chaining operator 的组合确保故障安全实现和故障安全访问任何通过的 属性 密钥路径在任何通过的 type/object ...

function getValueByKeyPath(obj, path) {
  return String(path)
    .split('.')
    .reduce((value, key) => value?.[key], Object(obj))
}

const sampleData = {
  foo: {
    value: 'foo',
    bar: {
      value: 'bar',
      baz: {
        value: 'baz',
      },
    },
  },
};

console.log(
  "getValueByKeyPath(sampleData, 'foo.bar.baz') ...",
  getValueByKeyPath(sampleData, 'foo.bar.baz')
);
console.log(
  "getValueByKeyPath(sampleData, 'foo.bar.baz.value') ...",
  getValueByKeyPath(sampleData, 'foo.bar.baz.value')
);

console.log(
  "\nfail safe ... getValueByKeyPath(sampleData, 'foo.biz.baz.value') ...",
  getValueByKeyPath(sampleData, 'foo.biz.baz.value')
);

console.log(
  "\nfail safe ... getValueByKeyPath('', 'toString') ...",
  getValueByKeyPath('', 'toString')
);
console.log(
  "fail safe ... getValueByKeyPath(null, '') ...",
  getValueByKeyPath(null, '')
);
console.log(
  "fail safe ... getValueByKeyPath() ...",
  getValueByKeyPath()
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

上述方法可以扩展到带有引号和不带引号的键的括号表示法,例如nested/mixed 基于对象和数组的数据结构。然后,在捕获括号内的值的同时,不只是在任何点处拆分键路径,而且在任何左括号和右括号处拆分键路径。此拆分操作的结果需要从一些伪造的工件中清除,减少部分保持不变 ...

function getValueByKeyPath(obj, path) {
  return String(path)
    .split(/\.|\[['"]?([^'"\]]*)['"]?\]/)
    .filter(elm => !!elm)
    .reduce((value, key) => value?.[key], Object(obj))
}

const sampleDataA = {
  foo: {
    value: 'foo',
    bar: {
      value: 'bar',
      baz: {
        value: 'baz',
      },
    },
  },
};
const sampleDataB = {
  foo: {
    bar: [{
      baz: {
        value: 'baz',
        biz: {
          value: 'biz',
        },
      }
    }, {
      buzz: {
        value: 'buzz',
        booz: {
          value: 'booz',
        },
      }
    }],
  },
};

console.log(
  "getValueByKeyPath(sampleDataA, 'foo.bar.baz.value') ...",
  getValueByKeyPath(sampleDataA, 'foo.bar.baz.value')
);
console.log(
  "getValueByKeyPath(sampleDataA, 'foo.bar[\"baz\"].value') ...",
  getValueByKeyPath(sampleDataA, 'foo.bar["baz"].value')
);
console.log(
  "getValueByKeyPath(sampleDataB, 'foo.bar[1][\"buzz\"].booz') ...",
  getValueByKeyPath(sampleDataB, 'foo.bar[1]["buzz"].booz')
);
console.log(
  "fail safe ... getValueByKeyPath(sampleDataB, 'foo.bar[2].buzz.booz') ...",
  getValueByKeyPath(sampleDataB, 'foo.bar[2].buzz.booz')
);
.as-console-wrapper { min-height: 100%!important; top: 0; }