Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing an Object.entries conversion

I am using Object.entries in order to get some values out of a nested object and filter it.

obj = Object.entries(obj)
  .filter(([k, v]) => {
    return true; // some irrelevant conditions here
  });

My object ends up as an array of arrays, of keys and vals.

[['key1', val]['key2', val']['key3', val]]

Is there a straightforward way to map these back into an object? The original object structure is:

{ key:val, key2:val2, key3:val3 }
like image 724
userqwert Avatar asked Apr 13 '18 00:04

userqwert


People also ask

How do you reverse an object key?

Use the Object. keys() method to get an array of the object's keys. Call the reverse() method to reverse the array. Use the forEach() method to iterate over the array and access the object's keys and values in reverse order.

Which is the valid example for object fromEntries () method?

fromEntries() method in JavaScript: Example 1: Conversion of a Map into an Object. Example 2: Conversion of a Array into an Object. Supported Browsers: The browsers supported by Object.

How do you convert an object to an array?

To convert an object to an array you use one of three methods: Object. keys() , Object. values() , and Object. entries() .


2 Answers

Sure, just use .reduce to assign to a new object:

const input = { key:'val', key2:'val2', key3:'val3' };

const output = Object.entries(input)
  .filter(([k, v]) => {
    return true; // some irrelevant conditions here
  })
  .reduce((accum, [k, v]) => {
    accum[k] = v;
    return accum;
  }, {});
console.log(output);

In modern browsers, you can also use Object.fromEntries which makes this even easier - you can just pass an array of entries, and it'll create the object from those entries.

const input = { key:'val', key2:'val2', key3:'val3' };

const output = Object.fromEntries(
  Object.entries(input)
    .filter(([k, v]) => {
      return true; // some irrelevant conditions here
    })
);
console.log(output);
like image 53
CertainPerformance Avatar answered Oct 19 '22 02:10

CertainPerformance


For new browsers, use Object.fromEntries:

Object.fromEntries(arr); 

For older js, it can still be a one liner.

arr.reduce((acc,[k,v])=>(acc[k]=v,acc),{})

Example:

Object.entries(sampleObject) // Turn object to array
   .reduce((acc,[k,v])=>(acc[k]=v,acc),{}) // Turn it back to object.
like image 35
chickens Avatar answered Oct 19 '22 04:10

chickens