Tengo el siguiente objeto JSON
[ { 'parameter-name': 'device', enabled: true, value: '077743322L102515', description: 'device identifier. Should be used only when multiple devices are connected at once' }, { 'parameter-name': 'app_id', enabled: true, value: 'com.instagram.andrpbj', description: ' when using this parameter, you are able to use Insomniac on a cloned Instagram-application. Just provide the new package name' }, { 'parameter-name': 'old', enabled: false, value: 'True', description: 'add this flag to use an old version of uiautomator. Use it only if you experience problems with the default version' } ]quería acceder al valor del nombre del parámetro: 'antiguo', por valor me refiero a valor ¿hay una solución de un solo paso para hacerlo sin iterar a través de cada entrada?
Desde mi punto de vista, usar Array.find() es la solución más limpia para obtener el valor:
const { value } = data.find((obj) => obj['parameter-name'] === 'old');Si su objetivo es editar el valor como lo solicita en el comentario, puede obtener el índice del objeto objetivo dentro de la matriz usando Array.findIndex() y luego editar los datos:
const objIdx = data.findIndex((obj) => obj['parameter-name'] === 'old'); data[objIdx].value = 'newValue'En lugar de obtener el índice, incluso podría manipular el valor del objeto directamente:
const obj = data.find((obj) => obj['parameter-name'] === 'old'); obj.value = 'newValue';Fragmento de código
const data = [{ 'parameter-name': 'device', enabled: true, value: '077743322L102515', description: 'device identifier. Should be used only when multiple devices are connected at once' }, { 'parameter-name': 'app_id', enabled: true, value: 'com.instagram.andrpbj', description: ' when using this parameter, you are able to use Insomniac on a cloned Instagram-application. Just provide the new package name' }, { 'parameter-name': 'old', enabled: false, value: 'True', description: 'add this flag to use an old version of uiautomator. Use it only if you experience problems with the default version' } ]; const obj = data.find((obj) => obj['parameter-name'] === 'old'); obj.value = 'newValue'; console.log(data);Para tener en cuenta una situación en la que no se encuentra el 'valor buscado', puede ser mejor dividir la asignación de esta manera:
const foundObj = data?.find((obj) => obj['parameter-name'] === 'old'); if (foundObj) foundObj.value = 'newValue'; const data = [{ 'parameter-name': 'device', enabled: true, value: '077743322L102515', description: 'device identifier. Should be used only when multiple devices are connected at once' }, { 'parameter-name': 'app_id', enabled: true, value: 'com.instagram.andrpbj', description: ' when using this parameter, you are able to use Insomniac on a cloned Instagram-application. Just provide the new package name' }, { 'parameter-name': 'old', enabled: false, value: 'True', description: 'add this flag to use an old version of uiautomator. Use it only if you experience problems with the default version' } ]; const foundObj = data?.find((obj) => obj['parameter-name'] === 'old'); if (foundObj) foundObj.value = 'newValue'; console.log(data);data.filter((value) => { if(value['parameter-name'] === 'old'){ console.log(value); } })Una alternativa a la respuesta de Alexander si no desea mutar el objeto de matriz directamente.
Es una función muy genérica que acepta un objeto de consulta (clave, valor anterior, valor nuevo), por lo que funcionará en todas las claves de propiedad, no solo parameter-name .
finds el objeto que coincide con los criterios de consulta (si no se encuentra nada, la función devuelve null ), filters los objetos que no coinciden con los criterios de consulta y luego devuelve esa matriz filtrada con un nuevo objeto actualizado.
const arr=[{"parameter-name":"device",enabled:!0,value:"077743322L102515",description:"device identifier. Should be used only when multiple devices are connected at once"},{"parameter-name":"app_id",enabled:!0,value:"com.instagram.andrpbj",description:" when using this parameter, you are able to use Insomniac on a cloned Instagram-application. Just provide the new package name"},{"parameter-name":"old",enabled:!1,value:"True",description:"add this flag to use an old version of uiautomator. Use it only if you experience problems with the default version"}]; // Accept an array, and a query object function change(arr, query) { // Destructure the query const { key, oldValue, newValue } = query; // Look for the object where the value // of the key specified in the query // matches the oldValue const found = arr.find(obj => { return obj[key] === oldValue; }); // If there isn't a match return null if (!found) return null; // Otherwise `filter` out the objects that // don't match the criteria... const filtered = arr.filter(obj => { return obj[key] !== oldValue; }); // Destructure all the object properties // away from the property we want to update const { [key]: temp, ...rest } = found; // Return a new array with a new updated object return [ ...filtered, { [key]: newValue, ...rest } ]; } const query = { key: 'parameter-name', oldValue: 'old', newValue: 'new' }; console.log(change(arr, query)); const query2 = { key: 'value', oldValue: '077743322L102515', newValue: '999999999' }; console.log(change(arr, query2));