我有一个像这样的对象数组:
damages: [
{
name: "Roof",
photos: [
{image_url: "http://www.url1.com"},
{image_url: "http://www.url2.com"},
{image_url: "http://www.url3.com"},
]
},
{
name: "Doors",
photos: [
{image_url: "http://www.url4.com"},
{image_url: "http://www.url5.com"},
{image_url: "http://www.url6.com"},
{image_url: "http://www.url7.com"}
]
}
]
如果我有image_url的值,我如何通过损坏来获取名称属性?
让我说我有这样的事情:
let image_url = "http://www.url6.com";
let name = damages.map(i => ....) //"Doors"
答案 0 :(得分:3)
你可以试试这样的东西吗?
var imgUrl = "http://www.url6.com";
for(var i = 0; i < damages.length; i++) {
for(var j = 0; j < damages[i].photos.length; j++) {
if(damages[i].photos[j].image_url === imgUrl) {
console.log(damages[i].name);
}
}
}
答案 1 :(得分:2)
X-Y
答案 2 :(得分:1)
您可以使用Array#find
和Array#some
function getName(url) {
return damages.find(a => a.photos.some(b => b.image_url === url)).name;
}
var damages = [{ name: "Roof", photos: [{ image_url: "http://www.url1.com" }, { image_url: "http://www.url2.com" }, { image_url: "http://www.url3.com" }, ] }, { name: "Doors", photos: [{ image_url: "http://www.url4.com" }, { image_url: "http://www.url5.com" }, { image_url: "http://www.url6.com" }, { image_url: "http://www.url7.com" }] }];
console.log(getName('http://www.url6.com'));