AbhiSam
AbhiSam

Reputation: 105

How to change array of object to different object in Javascript

I have Object below which I need to convert into below object format but can its possible to do that?

  products = {
      color: 'red',
      type: '2',
      status: 'true'
  }

converted object

  const filters = {
    color: color => color === 'red',
    type: type => type === '2' ,
    status: status => status === 'true',
  };

Upvotes: 0

Views: 54

Answers (3)

costaparas
costaparas

Reputation: 5237

You could loop over using Object.entries(), and add the comparison functions to the filters object.

Here is a working snippet, along with some test cases:

const products = {
  color: 'red',
  type: '2',
  status: 'true'
};

let filters = {};

for (const [k, v] of Object.entries(products)) {
  filters[k] = k => k === v;
}

console.log(filters);
console.log(filters['color']('red'));
console.log(filters['color']('blue'));
console.log(filters['type']('2'));
console.log(filters['type']('1'));
console.log(filters['status']('true'));
console.log(filters['status']('false'));

Upvotes: 0

Nick Parsons
Nick Parsons

Reputation: 50664

You can grab the product object's entires using Object.entries():

[["color", "red"], ["type", "2"], ["status", "true"]]

Once you have the entries, you can map over each inner array (ie: each key-value pair) using .map(). For each inner array, you can use destructuring assignment ([key, value]) => to extract both the first and second elements (ie: the key and the value) from the inner array. You can then return a new array, which contains your key in the first index, and a function as a value that checks for equality against the current value and the input argument to the function:

[
  [ "color", arg => arg === val ], 
  [ "type", arg => arg === val ], 
  [ "status", arg => arg === val ] 
]

The above inner arrays are still in the form of [key, value]. As this is the case, you can use Object.fromEntries() on the above array to convert it into an. object:

const products = { color: 'red', type: '2', status: 'true' };

const filters = Object.fromEntries(Object.entries(products).map(([key, val]) => [
  key, arg => arg === val 
]));

console.log(res);

The argument name doesn't match the name of the key, but that shouldn't matter as the argument is a variable

Upvotes: 1

Sandman
Sandman

Reputation: 1569

You can do this type of operation:

let products = {
  color: 'red',
  type: '2',
  status: 'true'
};
let filters = {};
Object.entries(products).forEach(e => {
  filters[e[0]] = f => f === products[e[0]];
});

Where filters is the object you expect.

Upvotes: 1

Related Questions