-1

I have an object

> state
{ homeStreet1: 'a', homeStreet2: 'b', homeStreet3: 'c', State: 'MA' }

> Object.entries(state)
[
  [ 'homeStreet1', 'a' ],
  [ 'homeStreet2', 'b' ],
  [ 'homeStreet3', 'c' ],
  [ 'State', 'MA' ]
]

How can I create a new object from this object that filters out an attribute?

I can do

> Object.entries(state).filter(([key,value]) => { return key !== 'homeStreet3' })

which gives me

> [ [ 'homeStreet1', 'a' ], [ 'homeStreet2', 'b' ], [ 'State', 'MA' ] ]

as a new array with the values I want, but how to get that as an object?

Michael Durrant
  • 93,410
  • 97
  • 333
  • 497
  • 1
    [`Object.fromEntries`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries) – VLAZ Aug 18 '20 at 13:41
  • Does this answer your question? [How to create an object from an Array of key-value pairs?](https://stackoverflow.com/questions/20059995/how-to-create-an-object-from-an-array-of-key-value-pairs) – jonrsharpe Aug 18 '20 at 14:20

3 Answers3

3

There are two ways that you could choose which fit yours the most

const arr = [
  ["homeStreet1", "a"],
  ["homeStreet2", "b"],
  ["State", "MA"],
]

const res1 = Object.fromEntries(arr)
const res2 = arr.reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {})

console.log(res1)
console.log(res2)
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
hgb123
  • 13,869
  • 3
  • 20
  • 38
2

The shortest approach is to take a destrcturing with a target for the unwanted property homeStreet3 and get the rest as result.

const
    state = { homeStreet1: 'a', homeStreet2: 'b', homeStreet3: 'c', State: 'MA' },
    { homeStreet3, ...result } = state;

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Expanding on this answer:

const arr = [
  ["homeStreet1", "a"],
  ["homeStreet2", "b"],
  ["State", "MA"],
]

const res1 = Object.fromEntries(arr)
const res2 = arr.reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {})

console.log(res1)
console.log(res2)
const filteredEntries = Object.entries(state).filter(([key]) => key !== 'homeStreet3')

// This
const newState = filteredEntries.reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {})

// Or this
const newState = Object.fromEntries(filteredEntries);
Joshua
  • 589
  • 1
  • 5
  • 19