Intentando, encuentre y devuelva un valor de una matriz usando JavaScript, con entradas dinámicas
const drawers = [ { "name": "locations", "values": [ { "value": "dana-point-ca", "label": "Dana Point, CA" }, { "value": "bronx-new-york", "label": "Bronx, New York" }, { "value": "new-york-ny", "label": "New York, NY" } ] }, { "name": "programAreas", "values": [ { "value": "coral-conservation", "label": "CORAL CONSERVATION" } ] } ] Las claves de entrada son dinámicas, si se trata de ubicaciones y el valor es bronx-new-york, entonces debería devolver Bronx, New York ;
let lbl = drawers.find(o => o.name === 'string 1').label;Use array.find en cada valor hasta que encuentre la respuesta.
const drawers = [ { "name": "locations", "values": [ { "value": "dana-point-ca", "label": "Dana Point, CA" }, { "value": "bronx-new-york", "label": "Bronx, New York" }, { "value": "new-york-ny", "label": "New York, NY" } ] }, { "name": "programAreas", "values": [ { "value": "coral-conservation", "label": "CORAL CONSERVATION" } ] } ] function getLabel(x) { for (const nameValues of drawers) { const values = nameValues.values const item = values.find(v => v.value === x) if (item !== undefined) { return item.label } } } getLabel("bronx-new-york") // 'Bronx, New York' getLabel("coral-conservation") // 'CORAL CONSERVATION' getLabel("Value that does not exist") // undefinedfor(let i = 0 ; i < drawers.length ; i++){ let lbl = drawers[i].values.find(o => o.label === "Bronx, New York").label; console.log(lbl) }Hay un par de formas de lograrlo. Como se muestra a continuación, obtendrá todos los resultados posibles. Sin embargo, es posible que deba deconstruir las matrices para obtener las cadenas.
const drawers = [ { "name": "locations", "values": [ { "value": "dana-point-ca", "label": "Dana Point, CA" }, { "value": "bronx-new-york", "label": "Bronx, New York" }, { "value": "new-york-ny", "label": "New York, NY" } ] }, { "name": "programAreas", "values": [ { "value": "coral-conservation", "label": "CORAL CONSERVATION" } ] } ] const enteredValue = "bronx-new-york"; const resultArrays = [] const onSearchLocation = () => { drawers.find(location => { const labels = location.values.map((place => { const array = []; if(place.value === enteredValue) { array.push(place.label); } if(array.length > 0) { resultArrays.push(array); } } )) })} onSearchLocation(); console.log(resultArrays);