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)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay