DEV Community

taiseen
taiseen

Posted on

convert [array] into {object} with needful value

Sometimes it is the requirement that, data come from an flat [array] & based on some needful condition, we need that [array] data into the {object} data-structure format, with some requirement values (as per your need), then this pieces of logic work good:-

array of data...

const basicControlKeys = ['tl', 'tr', 'bl', 'br'];
Enter fullscreen mode Exit fullscreen mode

converter function for [array] into {object}

// convert array data into object key with assign needful value...
const convertArrayIntoObject = (arrayData) => {

  const obj = {}; // empty object declaration...

  // iterate through every data inside array by for-of loop...
  for (let data of arrayData) 
  {
    obj[data] = true; // object value initialization...
  }

  return obj;
};
Enter fullscreen mode Exit fullscreen mode

calling the function & pass [array] into its parameter...

const result = convertArrayIntoObject(basicControlKeys);

console.log(result);

/*
{
  tl: true,
  tr: true,
  bl: true,
  br: true,
}
*/
Enter fullscreen mode Exit fullscreen mode

Top comments (0)