带有点表示法的文本属性返回未定义



我正在尝试传递一个变量并将其用作文本属性来对我的数据进行排序,但是,当变量具有多个带有点表示法的level时,locale将错误与undefined进行比较。

handleTableSort = (sortByColumn) => (event) => {
  event.preventDefault();
  const sortByColumn = 'name.first';
  const profileCandidates = this.state.profileCandidates.sort((a, b) => a[sortByColumn].localeCompare(b[sortByColumn]));
  this.setState({
   profileCandidates: profileCandidates
  })       
}

因此,当使用括号表示法访问属性时,javascript 将查找该确切键。所以通过说obj["name.first"],它是在字面上寻找那个键,所以它会匹配{"name.first": "bob"},但不是{name: {first: "bob"}}

要获得所需的行为,您必须手动分离每个部分。因此,获取任意属性键的简单函数可能是:

function getKeyAt(obj, key) {
    let result = obj;
    for (const part of key.split(".")) {
        if (!(part in result)) return; // If the key doesn't exist, return.
        result = result[part];
    }
    return result;
}

或者,如果您有可用的 lodash,它会提供一个方便的功能_.get为您执行此操作。

一旦你有了这样的函数,你的代码就可以像这样修改:

handleTableSort = (sortByColumn) => (event) => {
  event.preventDefault();
  const sortByColumn = 'name.first';
  const profileCandidates = this.state.profileCandidates.sort((a, b) => getKeyAt(a, sortByColumn).localeCompare(getKeyAt(b, sortByColumn));
  this.setState({
   profileCandidates: profileCandidates
  })       
}

据我所知,没有本机方法可以做到这一点,但代码非常简单:

const deref = (o, c) => {
    const _deref = (o, l) => l.length? _deref(o[l[0]], l.slice(1)): o;
    return _deref(o, c.split('.'));
};
...
  const profileCandidates = this.state.profileCandidates.sort((a, b)
       => a[sortByColumn].localeCompare(deref(b, sortByColumn)));

最新更新