Advertisement

TrimwebsolutionsTrimwebsolutions

Problem and Solutions

Accessing JSON value in array in Node.js ?

By M.K. Verma · 2 May 2022

Accessing JSON value in array in Node.js ?

It's a very generic function that accepts a query object (key, oldValue, newValue) so it will work on all the property keys, not just parameter-name.

It finds the object that matches the query criteria (if nothing is found the function returns null), filters out the objects that don't match the query criteria, and then returns that filtered array with a new updated object.

 

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));