Boky Boky - 1 month ago 12
React JSX Question

Get object property value from array of objects

I have an array of object like this :

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"}
]
}
]


If I have a value of image_url how can I loop through the damages to get a name property?

Let say that I have something like this :

let image_url = "http://www.url6.com";
let name = damages.map(i => ....) //"Doors"

Answer

You could use Array#find and 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'));