lodash在数组元素上检查对象属性

发布于 2025-02-11 22:11:52 字数 441 浏览 2 评论 0原文

我想使用lodash在特定数组元素上找到对象的属性。

可以说我正在击中API并获得响应,将其设置为React状态“ PersonsDetails”(其初始值为null),所以现在现在

let personsDetails=[{name:'king',id:2},{name:'queen',id:3}] //sometimes i get 1 object and sometimes 2

我想访问第二个对象的“名称”属性,我

personsDetails && personsDetails[1] && personsDetails[1].name

这样做了通过使用lodash访问它的任何简短语法?如果值不存在,

则据我所知,我需要null null _get属性仅适用于对象

I want to use lodash to find a property of an object at a specific array element.

Lets say I am hitting an api and getting response which sets it to the react state "personsDetails" (whose initial value was null), so now it becomes

let personsDetails=[{name:'king',id:2},{name:'queen',id:3}] //sometimes i get 1 object and sometimes 2

now when i want to access "name" property of 2nd object i do

personsDetails && personsDetails[1] && personsDetails[1].name

So is there any shorted syntax of accessing it via using lodash ? If the values doesnt exist i need null

As far as i know _get property works with object only so here i am dealing with array and then object

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

温暖的光 2025-02-18 22:11:52

您仍然可以使用获取并将默认值设置为null

let personsDetails=[{name:'king',id:2},{name:'queen',id:3}] 
let res = _.get(personsDetails, '1.name',null) //or _.get(personsDetails, '[1].name',null)
console.log(res)

console.log(_.get(undefined, '1.name',null))
console.log(_.get([], '1.name',null))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

或可以将nth一起使用,并将默认值设置为null

let personsDetails=[{name:'king',id:2},{name:'queen',id:3}] 

let res = _.get(_.nth(personsDetails,1),'name',null)
console.log(res)

console.log(_.get(_.nth([],1),'name',null))
console.log(_.get(_.nth(undefined,1),'name',null))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

You can still use get and set the default as null

let personsDetails=[{name:'king',id:2},{name:'queen',id:3}] 
let res = _.get(personsDetails, '1.name',null) //or _.get(personsDetails, '[1].name',null)
console.log(res)

console.log(_.get(undefined, '1.name',null))
console.log(_.get([], '1.name',null))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

or can use nth along with get and set the default as null

let personsDetails=[{name:'king',id:2},{name:'queen',id:3}] 

let res = _.get(_.nth(personsDetails,1),'name',null)
console.log(res)

console.log(_.get(_.nth([],1),'name',null))
console.log(_.get(_.nth(undefined,1),'name',null))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文