提问人:Hzzell4367 提问时间:6/8/2023 最后编辑:COLONEL FFHzzell4367 更新时间:6/8/2023 访问量:28
如何将列表中的值与另一个列表中的嵌套对象进行比较?
How do I compare a value from a list with a nested object in another list?
问:
我需要将 url 与 href test1 和 test2 中的值进行比较。我是 JavaScript 的新手,不确定如何循环以获取和比较值
“List1”: [
{
“type”: “text”,
“text”: “Test text”
},
“type”: “text”,
“text”: “test1”,
“marks”: [
{
“type”: “link”,
“attrs”: {
“href”: “test1”
}
}
]
},
“type”: “text”,
“text”: “test2”,
“marks”: [
{
“type”: “link”,
“attrs”: {
“href”: “test2”
}
}
]
}
]
->
for(let I = 0; I < content.length; I++) {
if(my_url === content[I].marks[0].attrs.href {
Do something….
}
}
答:
0赞
yanir midler
6/8/2023
#1
您可以尝试以下代码:
// Assuming `content` is the JavaScript object you provided
// The URL you want to compare
const my_url = "https://example.com/test1";
// Loop through the "List1" array
for (let i = 0; i < content.List1.length; i++) {
const item = content.List1[i];
// Check if the item has "marks" property and it is an array
if (item.marks && Array.isArray(item.marks)) {
// Loop through the "marks" array
for (let j = 0; j < item.marks.length; j++) {
const mark = item.marks[j];
// Check if the "attrs" property exists and it has the "href" property
if (mark.attrs && mark.attrs.href) {
// Compare the URL with the "href" value
if (my_url === mark.attrs.href) {
// URL matches, do something
console.log("URL match found!");
console.log("Text:", item.text);
console.log("Type:", item.type);
// You can perform additional actions here
}
}
}
}
}
评论