Select only specific properties from an array of objects

Viewed 3698

Let's say I create object like this:

updates.push({
      id: this.ids[i],
      point: point,
      value: value
    });

Later on I want to use JSON.stringify on updates object, however I need only point and value like:

updates[{point: 1, value: 12}, {point: 2, value: 24}]

What's the best ES6 solution for that?

I looked at some examples with delete, but that's not what I actually need, as I do not want to delete ids.

3 Answers

Try the following :

JSON.stringify(updates.map(({point,value})=>({point,value})));

let updates = [{id : 1, point : 1, value: 2},{id : 1, point : 1, value: 2}];
console.log(JSON.stringify(updates.map(({point,value})=>({point,value}))));

If updates is an array. Then you might want something like this:

const newArrayWithoutId = updates.map(({ point, value }) => {
  return {
    point,
    value,
  }
}

Just ({id, ...rest}) => ({...rest}) is too short for an answer, so how about this?

const withoutId = ({id, ...rest}) => ({...rest})

const vals = [
  {id: 'a', point: 1, value: 'foo'},
  {id: 'b', point: 2, value: 'bar'},
  {id: 'c', point: 3, value: 'baz', meaning: 42}
]

const reduced = vals.map(withoutId)

console.log(reduced)

Related