gpt4 book ai didi

javascript - 带点符号的文字属性返回未定义

转载 作者:行者123 更新时间:2023-12-03 02:46:34 26 4
gpt4 key购买 nike

我试图传递一个变量并将其用作文字属性来对我的数据进行排序,但是,当该变量有多个 level 时使用点符号将 localeCompare 错误与 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
})
}

关于javascript - 带点符号的文字属性返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48069511/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com