我正在尝试循环访问一个对象 (objectToLoop
) 并检查是否包含键 comments_text
。如果是,我想检查 comments_text
,如果 comments_text
中的 key
与 commentId
匹配,我想将 let item
设置为 comments_text
中的整个对象。
我尝试将 let item
设置为以下内容,但出现“未定义”:
{
commenter_comment: "reedwe",
commenter_handle: "FALCON1",
commenter_uid: "ZALb0B3wZEWjfdFIUOxteJRl9Xu1",
key: "-MlaKXBMXzXIBJMsZQNX"
}
感谢建议和反馈。
const commentId = "-MlaKXBMXzXIBJMsZQNX"
const objectToLoop = {
comment: false,
comments_text: {
commenter_comment: "reedwe",
commenter_handle: "FALCON1",
commenter_uid: "ZALb0B3wZEWjfdFIUOxteJRl9Xu1",
key: "-MlaKXBMXzXIBJMsZQNX"
},
handle: "TURTLE1",
key: "-MkeOOUboKdOcC3Sannl",
title: "hello2"
}
function returnMatchingComment(commentIdKey) {
let item;
for (const post in objectToLoop) {
if (post.comments_text) {
item = Object.values(post.comments_text).find(
(comment) => comment.key === commentIdKey
)
};
if (item) {
break;
}
}
return item
}
console.log(
returnMatchingComment(commentId)
)
最佳答案
您不需要使用for...in
循环。您可以首先使用 Object.prototype.hasOwnProperty()
检查 objectToLoop
是否具有属性 comments_text
并检查是否 objectToLoop?.comments_text?.key == commentId
。我使用了 ?.
(可选链接),这样如果 objectToLoop.comments_text
不存在,它只会返回 undefined
而不会抛出丑陋的错误错误。
示例:
const commentId = "-MlaKXBMXzXIBJMsZQNX"
const objectToLoop = {
comment: false,
comments_text: {
commenter_comment: "reedwe",
commenter_handle: "FALCON1",
commenter_uid: "ZALb0B3wZEWjfdFIUOxteJRl9Xu1",
key: "-MlaKXBMXzXIBJMsZQNX"
},
handle: "TURTLE1",
key: "-MkeOOUboKdOcC3Sannl",
title: "hello2"
}
if(objectToLoop.hasOwnProperty('comments_text') && objectToLoop?.comments_text?.key == commentId) {
let item = objectToLoop.comments_text;
console.log(item)
}
objectToLoop.hasOwnProperty('comments_text')
,就像可选链接一样(如前所述),objectToLoop?.comments_text?.key == commentId<如果 objectToLoop.comments_text
不存在,
将返回 undefined
;如果 objectToLoop.comments_text.key
,则返回 false
不等于commentId
。 示例2:
const commentId = "-MlaKXBMXzXIBJMsZQNX"
const objectToLoop = {
comment: false,
comments_text: {
commenter_comment: "reedwe",
commenter_handle: "FALCON1",
commenter_uid: "ZALb0B3wZEWjfdFIUOxteJRl9Xu1",
key: "-MlaKXBMXzXIBJMsZQNX"
},
handle: "TURTLE1",
key: "-MkeOOUboKdOcC3Sannl",
title: "hello2"
}
if(objectToLoop?.comments_text?.key == commentId) {
let item = objectToLoop.comments_text;
console.log(item)
}
关于javascript - For in 对象上的循环,以及 .find,返回 "undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69536957/